This post will discuss how to replace a character at a specific position in a string in C#.

The strings are immutable in C#. That means we cannot change their values once they are created. The only feasible solution is to create a new string object with the replaced character. There are several ways to replace the character at a specific position in a string:

1. Using StringBuilder() method

The recommended solution is to use the StringBuilder class to efficiently replace the character at a specific index in a string in C#, as shown below:

Download  Run Code

2. Using String.Remove() method

To replace the character present at a specific index in the string, the idea is to remove the character present at a given position in the string and then insert the specified character at the very same position.

Download  Run Code

3. Using String.Substring() method

We can use the String.Substring() method to partition the string into two halves consisting of substring before and after the character to be replaced. Once we have isolated the character to be replaced, we can use the concatenation operator to build the final string, as shown below:

Download  Run Code

4. Using Character Array

Another approach is to convert the given string to a mutable character array and then replace the character present at the specified index. Finally, convert the character array back into a string using the string constructor.

Download  Run Code

That’s all about replacing the character at a specific position in a string in C#.