字符串行数Trim()可以去掉字符串前后的空格,如:
C# Code

string myString = " this is a test "; Console.WriteLine(myString.Trim());
输出的结果为:
使用字符串的Replace()函数可以去掉字符串中间及前后的空格:
C# Code

string myString = " this is a test "; Console.WriteLine(myString.Replace(" ", ""));
输出的结果为:
然而,当字符串中含转义字符(如
, ,
)时,Replace函数输出的结果中还是有空格,如:
C# Code

string myString = " this is a test "; Console.WriteLine(myString.Trim());
输出结果为:
此时当然可以用多个Replace函数来替换这些空格,但稍显麻烦。
此时可以考虑用正则表达式方法Regex.Replace()和匹配符s(匹配任何空白字符,包括空格,制表符,换页符等,与[f v]等效),如:
C# Code

string myString = " this is a test "; Console.WriteLine(Regex.Replace(myString, @"s", ""));
输出结果为: