remove a character from a string in csharp

One way to remove a character from a string in C# is to use the Substring method along with the Remove method. Here is an example:

main.cs
string myString = "Hello World!";
int charIndex = myString.IndexOf('o');
if (charIndex >= 0)
{
    myString = myString.Remove(charIndex, 1);
}
Console.WriteLine(myString); // prints "Helo World!"
196 chars
8 lines

In this example, we first find the index of the character to remove using the IndexOf method. If the character is found (charIndex >= 0), we remove it using the Remove method. We provide the starting index of the character to remove and specify the number of characters to remove (in this case, just 1).

Note that this approach only removes the first occurrence of the character in the string. If you need to remove all occurrences of the character, you can use a loop or regular expression.

gistlibby LogSnag