You probably know that you can use
String.Trim
The method of removing the tail and head space string, not fortunately This
Trim
The method can not remove the intermediate space, such as a string:
string
text
=
"
My test\nstring\r\n is\t quite long
"
;
string trim = text.Trim();
The
'trim'
string will be:
string trim = text.Trim();
"
My test\nstring\r\n is\t quite long
"
(
31
characters)
Another approach is to use
String.Replace
method, but this requires you to remove individual spaces by calling multiple methods:
string
trim
=
text.Replace(
"
"
,
""
);
trim = trim.Replace( " \r " , "" );
trim = trim.Replace( " \n " , "" );
trim = trim.Replace( " \t " , "" );
The best method here is to use regular expressions. You can use
Regex.Replace
method, it will replace all occurrences of the specified character. In this example, use regular expression matching character "\ s", it will match any spaces included in this string in space, tab characters, line breaks, and new line (newline).
trim = trim.Replace( " \r " , "" );
trim = trim.Replace( " \n " , "" );
trim = trim.Replace( " \t " , "" );
string
trim
=
Regex.Replace( text,
@"
\s
"
,
""
);
The
'trim'
string will be:
"
Myteststringisquitelong
"
(
23
characters)
Reproduced in: https: //www.cnblogs.com/yangjie5188/archive/2008/04/11/1148460.html