Replacing a char at a given index in string?

string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);

Use a StringBuilder:

StringBuilder sb = new StringBuilder(theString);
sb[index] = newChar;
theString = sb.ToString();

The simplest approach would be something like:

public static string ReplaceAt(this string input, int index, char newChar)
{
    if (input == null)
    {
        throw new ArgumentNullException("input");
    }
    char[] chars = input.ToCharArray();
    chars[index] = newChar;
    return new string(chars);
}

This is now an extension method so you can use:

var foo = "hello".ReplaceAt(2, 'x');
Console.WriteLine(foo); // hexlo

It would be nice to think of some way that only required a single copy of the data to be made rather than the two here, but I'm not sure of any way of doing that. It's possible that this would do it:

public static string ReplaceAt(this string input, int index, char newChar)
{
    if (input == null)
    {
        throw new ArgumentNullException("input");
    }
    StringBuilder builder = new StringBuilder(input);
    builder[index] = newChar;
    return builder.ToString();
}

... I suspect it entirely depends on which version of the framework you're using.

Tags:

C#

String