正则表达式,如果字符串中间还有连续空格的话,仅保留一个空格,即允许字符串中间有多个空格,但连续的空格数不可超过一个

string input = " xx xxn ";
Console.WriteLine("操作前input={0},长度={1}",input,input.Length); //去除重复空格,连续空格替换为单个空格
input = Regex.Replace(input.Trim(), "\\s+", " ");
Console.WriteLine("操作后input={0},长度={1}", input, input.Length);

原文地址:https://www.cnblogs.com/wangchuang/p/2918633.html