C# Program to replace a special character from a String

The Replace() method in C# is used to replace all occurrences of a specified character or substring in a string with a new character or substring. This method is particularly useful for removing or replacing special characters from strings.

Syntax

Following is the syntax for replacing characters using the Replace() method −

string.Replace(oldChar, newChar)
string.Replace(oldString, newString)

Parameters

  • oldChar/oldString − The character or string to be replaced.

  • newChar/newString − The character or string to replace with.

Return Value

The Replace()

Using Replace() to Replace Special Characters

Example 1 - Replacing a Single Special Character

using System;

public class Program {
   public static void Main() {
      string str = "abcd$ef$gh";
      Console.WriteLine("Initial string = " + str);
      
      string res = str.Replace('$', 'k');
      Console.WriteLine("Replaced string = " + res);
   }
}

The output of the above code is −

Initial string = abcd$ef$gh
Replaced string = abcdkefkgh

Example 2 - Replacing Multiple Different Special Characters

using System;

public class Program {
   public static void Main() {
      string str = "Hello@World#2023!";
      Console.WriteLine("Initial string = " + str);
      
      string res = str.Replace('@', '_')
                     .Replace('#', '-')
                     .Replace('!', '.');
      
      Console.WriteLine("Replaced string = " + res);
   }
}

The output of the above code is −

Initial string = Hello@World#2023!
Replaced string = Hello_World-2023.

Example 3 - Removing Special Characters

using System;

public class Program {
   public static void Main() {
      string str = "C#-Programming*Tutorial!";
      Console.WriteLine("Initial string = " + str);
      
      string res = str.Replace("-", "")
                     .Replace("*", "")
                     .Replace("!", "");
      
      Console.WriteLine("After removing special chars = " + res);
   }
}

The output of the above code is −

Initial string = C#-Programming*Tutorial!
After removing special chars = C#ProgrammingTutorial

Key Rules

  • The Replace() method is case-sensitive and replaces all occurrences.

  • It returns a new string object; the original string is not modified.

  • If the character or substring to replace is not found, the original string is returned unchanged.

  • You can chain multiple Replace() calls to replace different characters.

Conclusion

The Replace() method in C# provides a simple and effective way to replace or remove special characters from strings. It returns a new string with all occurrences of the specified character or substring replaced, making it ideal for string cleanup and formatting operations.

Updated on: 2026-03-17T07:04:35+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements