replace a character in a string in csharp

To replace a character in a string in C#, we can use the string.Replace() method. Here's an example:

main.cs
string originalString = "Hello World!";
char charToReplace = 'o';
char replacementChar = 'x';

int charIndex = originalString.IndexOf(charToReplace); // Get the index of the character to replace
if (charIndex >= 0) // If the character is found in the string
{
    string newString = originalString.Remove(charIndex, 1).Insert(charIndex, replacementChar.ToString()); // Remove the character at the index and replace it with the new character
    Console.WriteLine(newString); // Output the new string
}
else
{
    Console.WriteLine("Character not found in string."); // Output an error message if the character is not found
}
625 chars
15 lines

In this example, we have declared a string variable originalString and assigned it the value "Hello World!". We have also declared two char variables: charToReplace with value 'o', and replacementChar with value 'x'.

Next, we use originalString.IndexOf(charToReplace) method to get the index of the character to be replaced. The IndexOf() method searches the string for the first occurrence of the specified character and returns its index. If the character is not found, it returns -1.

If the character is found, we remove the character using the Remove() method which takes the starting index and number of characters to remove as arguments. Then, we use the Insert() method to insert the new character at the same index using the charIndex and replacementChar.ToString().

Finally, we output the new string with the Console.WriteLine() method. If the character is not found, we output an error message.

gistlibby LogSnag