SoFunction
Updated on 2025-03-06

C# implements the method of removing spaces in Strings

This article describes the method of removing spaces in Strings in C#, and is shared with you for your reference. The specific implementation method is as follows:

Generally speaking, you may know that you can use methods to remove the spaces at the beginning and end of a string, unfortunately.This Trim method cannot remove C# spaces in the middle of a string

The sample code is as follows:

Copy the codeThe code is as follows:
string text = "  My test\nstring\r\n is\t quite long  "; 
string trim = ();

This 'trim' string will be:

Copy the codeThe code is as follows:
"My test\nstring\r\n is\t quite long"  (31 characters)

Another way to clear C# spaces isHow to use, but this requires you to remove individual C# spaces by calling multiple methods:

Copy the codeThe code is as follows:
string trim = ( " ", "" ); 
trim = ( "\r", "" ); 
trim = ( "\n", "" ); 
trim = ( "\t", "" );

The best way here isUsing regular expressions.You can use the method, which replaces all matching characters with the specified characters. In this example, using the regular expression match character "\s", it will match any spaces contained in the string C# spaces, tab characters, newlines, and newlines.

Copy the codeThe code is as follows:
string trim = ( text, @"\s", "" );

This 'trim' string will be:

Copy the codeThe code is as follows:
"Myteststringisquitelong"  (23 characters)

I hope this article will be helpful to everyone's C# programming.