C# 去掉字符串多余空格
将字符串" hello world,你 好 世界 ! "两端空格去掉,并且将其中的所有其他空格都替换成一个空格,输出结果为:"hello world,你 好 世界 !"。
用Split方法,有很多的重载;然后用Join方法进行连接成新字符串。
string msgTrim = msg.Trim();  // 去掉两端的空格,返回副本。
string msg = "  hello      world,你  好 世界   !    ";
string[] words = msg.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
msg = String.Join(" ", words);
Console.WriteLine("===" + msg + "==");
Console.ReadKey();
输出:
===hello world,你 好 世界 !==
参考:
1.link-01
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号