Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
replace
string
communitycreator

How to replace a string with another string in C# using replace()

Theodore Kelechukwu Onyejiaku

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.

Syntax

string.replace(rem, rep)

Parameters

  • 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.

Return value

The return value is a new string.

Example

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

c#
replace
string
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring