how do I set a character at an index in a string in c#?

Viewed 40749
someString[someRandomIdx] = 'g';

will give me an error.

How do I achieve the above?

7 Answers

Since no one mentioned a one-liner solution:

someString = someString.Remove(index, 1).Insert(index, "g");

If you're willing to introduce Also(...):

public static T Also<T>(this T arg, Action<T> act) { act(arg); return arg; }

public static string ReplaceCharAt(this string str, int index, char replacement) =>
    new string(str.ToCharArray().Also(arr => arr[index] = replacement));
Related