C# Replace or Remove Char by Index
Replace or remove a char at a given index (position) in a string
Strings in c# are immutable objects - it's not possible to replace or remove a char directly.
// Sample: We want to replace
d with X
string somestring = "abcdefg";
somestring[3] = 'X';
Results in error: "Property or indexer
cannot be assigned to - it is read only"
The solution is to create
a new string with the given char replaced or removed.
Replace
There are multiple ways to achieve the replacement, e.g. using StringBuilder
or String.ToCharArray();
Important: Don't forget to make sure the string
is not empty or too short - otherwise you would get an exception!
// Sample: We want to replace
'd' with 'X' (index=3)
string somestring = "abcdefg";
StringBuilder
sb = new StringBuilder(somestring);
sb[3] = 'X';
// index starts at 0!
somestring = sb.ToString();
or
// Sample: We want to replace
'd' with 'X' (index=3)
string somestring = "abcdefg";
char[] ch
= somestring.ToCharArray();
ch[3] = 'X'; //
index starts at 0!
string newstring = new string (ch);
Remove 1 Char at a given Index
// Sample: We want to remove
'd' (index=3)
// Don't forget to make sure the string is not empty or too
short
string somestring = "abcdefg";
StringBuilder sb = new StringBuilder(somestring);
sb.Remove(3, 1);
somestring = sb.ToString();
Remove multiple Chars at a given Index
// Sample: We want to remove
3 chars "cde"(index=2-4)
// Don't forget to make sure the string is not empty
or too short
string somestring = "abcdefg";
StringBuilder sb =
new StringBuilder(somestring);
sb.Remove(2, 3);
somestring = sb.ToString();