Replacing a string with another string is possible in C#, just like in other programming languages. To do this, we use the replace()
method. It replaces any occurrence of the given string or character with another one specified.
string.replace(rem, rep)
rem
: This is the character or string you want to remove.rep
: This is the character or string you want to use as a replacement.The return value is a new string.
In the example below, we will demonstrate the use of the replace()
method. We will create a string and replace some strings and characters in it.
// create class class StringReplacer { // create main method static void Main() { // create string string str = "This, was C#"; // replace some characters and strings string rep1 = str.Replace("was", "is"); string rep2 = str.Replace(",", ""); System.Console.WriteLine(rep1); System.Console.WriteLine(rep2); } }
In the code above, we first replaced was
with is
. We also replaced ,
with whitespace.
RELATED TAGS
CONTRIBUTOR
View all Courses