To replace a character in a string in C#, we can use the string.Replace()
method. Here's an example:
main.cs625 chars15 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