Replace character at a specific position in a string in C#
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System; using System.Text; public class Example { public static void Main() { string str = "techie"; int pos = 0; char replacement = 'T'; StringBuilder sb = new StringBuilder(str); sb[pos] = replacement; str = sb.ToString(); Console.WriteLine(str); } } /* Output: Techie */ |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void Main() { string str = "techie"; int pos = 0; char replacement = 'T'; str = str.Remove(pos, 1).Insert(pos, replacement.ToString()); Console.WriteLine(str); } } /* Output: Techie */ |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class Example { public static void Main() { string str = "techie"; int pos = 0; char replacement = 'T'; str = str.Substring(0, pos) + replacement + str.Substring(pos + 1); Console.WriteLine(str); } } /* Output: Techie */ |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Example { public static void Main() { string str = "techie"; int pos = 0; char replacement = 'T'; char[] chars = str.ToCharArray(); chars[pos] = replacement; str = new string(chars); Console.WriteLine(str); } } /* Output: Techie */ |
That’s all about replacing the character at a specific position in a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)