Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- class Program
- {
- static void Main()
- {
- string sentence = "Hello how are you?";
- string targetWord = "how";
- string replaceWith = "what is";
- string indent = " ";
- // Calculate lengths
- int originalLength = sentence.Length;
- int targetLength = targetWord.Length;
- int replacementLength = replaceWith.Length;
- int indentLength = indent.Length;
- // Calculate the length for the new sentence
- int newLength = originalLength - targetLength + replacementLength + (indentLength * 6); // 6 indentations
- Span<char> originalSpan = stackalloc char[originalLength];
- Span<char> newSpan = stackalloc char[newLength];
- // Copy original sentence and target word to spans
- sentence.AsSpan().CopyTo(originalSpan);
- targetWord.AsSpan().CopyTo(stackalloc char[targetLength]);
- int newSpanIndex = 0;
- // Add initial indentation
- CopyAndAdvance(ref newSpan, indent.AsSpan(), ref newSpanIndex);
- // Find and replace target word, add indentations
- for (int i = 0; i < originalSpan.Length; i++)
- {
- if (IsWordMatch(originalSpan.Slice(i, originalSpan.Length - i), targetWord.AsSpan()))
- {
- CopyAndAdvance(ref newSpan, replaceWith.AsSpan(), ref newSpanIndex);
- i += targetLength - 1; // Skip the target word in original sentence
- }
- else
- {
- newSpan[newSpanIndex++] = originalSpan[i];
- }
- // Add indentation after each word or at the end
- if (i == originalSpan.Length - 1 || originalSpan[i] == ' ')
- {
- CopyAndAdvance(ref newSpan, indent.AsSpan(), ref newSpanIndex);
- }
- }
- // Convert result back to string
- string result = new string(newSpan);
- Console.WriteLine($"Original: {sentence}");
- Console.WriteLine($"Modified: {result}");
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static void CopyAndAdvance(ref Span<char> destination, ReadOnlySpan<char> source, ref int index)
- {
- source.CopyTo(destination.Slice(index));
- index += source.Length;
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static bool IsWordMatch(ReadOnlySpan<char> sentence, ReadOnlySpan<char> word)
- {
- return sentence.Length >= word.Length && sentence.Slice(0, word.Length).SequenceEqual(word);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement