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 remove whitespaces in a string
In C#, there are several ways to remove whitespaces from a string. You can remove all spaces, only leading and trailing spaces, or all types of whitespace characters including tabs and newlines.
Using String.Replace() Method
The The output of the above code is − For mutable strings, you can use The output of the above code is − The The output of the above code is − To remove all types of whitespace including spaces, tabs, and newlines, you can use regular expressions − The output of the above code is − Use Replace()
string result = originalString.Replace(" ", "");
Example
using System;
class Demo {
static void Main() {
string str = "Patience is key!";
Console.WriteLine("Original String: " + str);
string result = str.Replace(" ", "");
Console.WriteLine("After removing spaces: " + result);
}
}
Original String: Patience is key!
After removing spaces: Patienceiskey!
Using StringBuilder.Replace() Method
StringBuilder which modifies the string in-place −Example
using System;
using System.Text;
class Demo {
static void Main() {
StringBuilder str = new StringBuilder("Patience is key!");
Console.WriteLine("Original String: " + str.ToString());
str.Replace(" ", "");
Console.WriteLine("After removing spaces: " + str.ToString());
}
}
Original String: Patience is key!
After removing spaces: Patienceiskey!
Using String.Trim() Method
Trim() method removes whitespace only from the beginning and end of a string −Example
using System;
class Demo {
static void Main() {
string str = " Patience is key! ";
Console.WriteLine("Original String: '" + str + "'");
string result = str.Trim();
Console.WriteLine("After trimming: '" + result + "'");
}
}
Original String: ' Patience is key! '
After trimming: 'Patience is key!'
Removing All Whitespace Characters
Example
using System;
using System.Text.RegularExpressions;
class Demo {
static void Main() {
string str = "Patience\t is <br> key!";
Console.WriteLine("Original String: " + str);
string result = Regex.Replace(str, @"\s+", "");
Console.WriteLine("After removing all whitespace: " + result);
}
}
Original String: Patience is
key!
After removing all whitespace: Patienceiskey!
Comparison of Methods
Method
Purpose
Performance
String.Replace()
Remove specific characters
Fast for simple replacements
StringBuilder.Replace()
In-place modification
Best for multiple operations
String.Trim()
Remove leading/trailing whitespace
Very fast
Regex.Replace()
Remove all whitespace types
Slower but more flexible
Conclusion
Replace() for removing specific characters like spaces, Trim() for leading/trailing whitespace, and Regex.Replace() for comprehensive whitespace removal. Choose StringBuilder when performing multiple string modifications for better performance.
