How to remove all spaces in C# string

String line number Trim() can remove the spaces before and after the string, such as:

 

 C# Code 
string myString = "  this is a test   ";
Console.WriteLine(myString.Trim());
View Code

The output is:

 

Use the Replace() function of a string to remove spaces in the middle and before and after the string:

 C# Code 
string myString = "  this is a test  ";
Console.WriteLine(myString.Replace(" ", ""));
View Code

The output is:

However, when the string contains escape characters (such as \r, \t, \n), there are still spaces in the output of the Replace function, such as:

 C# Code 
string myString = "  this\n is\r a \ttest   ";
Console.WriteLine(myString.Trim());
View Code

The output is:

At this point, of course, you can use multiple Replace functions to replace these spaces, but it is slightly troublesome.

At this point, you can consider using the regular expression method Regex.Replace() and the matching character \s (match any whitespace character, including spaces, tabs, form feeds, etc., and [\f\n\t\r\v] equivalent), such as:

 

 C# Code 
string myString = "  this\n is\r a \ttest   ";
Console.WriteLine(Regex.Replace(myString, @"\s", ""));
View Code

The output is:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325022509&siteId=291194637