To replace characters in a string in C#, you can use the Replace()
method of the string
class. The Replace()
method returns a new string in which all occurrences of a specified character or string in the current string are replaced with another specified character or string.
Here is an example of how to use the Replace()
method to replace characters in a string:
main.cs123 chars4 lines
In the above example, we first create a string str
containing the text "Hello World!". We then call the Replace()
method on this string to replace all occurrences of the character 'o' with the character '0'. The resulting string is stored in the newStr
variable, which we then output to the console.
You can also use the Substring()
method to extract a portion of the original string and then use the Replace()
method on the extracted substring. Here is an example:
main.cs237 chars6 lines
In the above example, we first extract the substring "Hello" from the original string using the Substring()
method. We then replace all occurrences of the character 'l' with the character '1' in the extracted substring using the Replace()
method. We then call the Replace()
method on the original string to replace the original substring with the modified substring. The resulting string is stored in the newStr
variable, which we then output to the console.
gistlibby LogSnag