Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 The output of the above code is − The output of the above code is − The output of the above code is − The 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 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);
}
}
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);
}
}
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);
}
}
Initial string = C#-Programming*Tutorial!
After removing special chars = C#ProgrammingTutorial
Key Rules
Replace() method is case-sensitive and replaces all occurrences.Replace() calls to replace different characters.Conclusion
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.
