C# 去掉多余空格

将字符串” hello world,你 好 世界 ! “两端空格去掉,并且将其中的所有其他空格都替换成一个空格,输出结果为:”hello world,你 好 世界 !”。

Split方法,有很多的重载;然后用Join方法进行连接成新字符串。

string msgTrim = msg.Trim(); // 去掉两端的空格,返回副本。

1
2
3
4
5
6
7
8
string msg = "  hello      world,你  好 世界   !    ";

string[] words = msg.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

msg = String.Join(" ", words);
Console.WriteLine("===" + msg + "==");

Console.ReadKey();

输出:

1
===hello world,你 好 世界 !==




参考:
1.link-01

感谢支持!