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 classclass StringReplacer{// create main methodstatic void Main(){// create stringstring str = "This, was C#";// replace some characters and stringsstring 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.