Home > database >  How to replace a character with string in Span<char>?
How to replace a character with string in Span<char>?

Time:12-10

I'm currently trying to replace few specific characters with other characters in Span<char>. In my case, I'm trying to replace a space with _ and ' with &27. Should I just

Span<char>.ToString().Replace("'", "&27")

at end of the method?

Span<char> span = stackalloc char[byte.MaxValue];
for (int i = 0, c = name.Length; i < c; i  ) {
    char old = name[i];
    span[i] = old switch {
        ' ' => '_',
        '\'' => char.MinValue,
        _ => name[i]
    };

    if (span[i] is char.MinValue) {
        ReadOnlySpan<char> a = span[(i   1)..^2];
        span[i] = '&';
        span[i   1] = '2';
        span[i   2] = '7';
        span[(i   3)..^2] = a;
    }
}

return span.ToString();

I tried that, but Visual Studio gives an error at span[(i 3)..^2].

CodePudding user response:

To replace characters in a Span, you can use the Replace method. Here's an example:

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var text = "Hello World";
            var span = text.AsSpan();

            // Replace space with _
            span = span.Replace(' ', '_');
            Console.WriteLine(span.ToString()); // "Hello_World"

            // Replace ' with &27
            span = span.Replace('\'', '&27');
            Console.WriteLine(span.ToString()); // "Hello_World&27"
        }
    }
}

Note that the Replace method creates a new Span instance with the replaced characters. It does not modify the original Span in place.

CodePudding user response:

I haven't worked with the Span struct before, but couldn't you just replace the characters in the string before adding them to the Span? We could create a temporary string if we don't want to modify the original:

var tempName = name.Replace(" ", "_").Replace("'", "&27");
Span<char> span = stackalloc char[byte.MaxValue];
for (var i = 0; i < tempName.Length; i  ) span[i] = tempName[i];
  • Related