replave characters in string in csharp

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.cs
string str = "Hello World!";
string newStr = str.Replace('o', '0');
Console.WriteLine(newStr);   // Outputs "Hell0 W0rld!"
123 chars
4 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.cs
string str = "Hello World!";
string substr = str.Substring(0, 5);    // Extracts "Hello"
string newSubstr = substr.Replace('l', '1');
string newStr = str.Replace(substr, newSubstr);
Console.WriteLine(newStr);   // Outputs "He11o World!"
237 chars
6 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