C implements the method of removing whitespace from Strings

  • 2020-12-05 17:20:25
  • OfStack

This article describes the C# implementation of Strings whitespace removal method, to share for your reference. Specific implementation methods are as follows:

In general, you probably know that you can use the String.Trim method to remove Spaces at the beginning and end of a string, unfortunately. The Trim method does not remove the C# space in the middle of the string.

The sample code is as follows:

string text = "  My test\nstring\r\n is\t quite long  ";  
string trim = text.Trim();

The 'trim' string would be:

"My test\nstring\r\n is\t quite long"  (31 characters)

Another way to clear C# whitespace is to use the String.Replace method, but this requires you to remove individual C# whitespace by calling multiple methods:

string trim = text.Replace( " ", "" );  
trim = trim.Replace( "\r", "" ); 
trim = trim.Replace( "\n", "" ); 
trim = trim.Replace( "\t", "" );

The best approach here is to use regular expressions. You can use the Regex.Replace method, which replaces all matches with the specified character. In this example, use the regular expression match "\s", which matches any Spaces contained in the string C# Spaces, tab characters, newline characters, and new lines (newline).

string trim = Regex.Replace( text, @"\s", "" );

The 'trim' string would be:

"Myteststringisquitelong"  (23 characters)

I hope this article has been helpful for your C# programming.


Related articles: