1. 程式人生 > >字串中連續多個空格合併成一個空格

字串中連續多個空格合併成一個空格

 public string UnitMoreSpan(string str)
        {
            string originStr = str;
            string newStr = "";
            string[] splits = originStr.Split(' '); //以空格為標誌
            for (int i = 0; i < splits.Length; i++)
            {
                if (splits[i].Trim().Equals(""))  //這裡不是空格
                {
                    continue;
                }
                else
                {
                    if (i == splits.Length - 1)
                    {
                        newStr += splits[i];
                    }
                    else
                    {
                        newStr += splits[i] + " ";  //這裡加一個空格
                    }
                }
            }
            if (newStr.LastIndexOf(' ') == newStr.Length - 1)
            {
                newStr = newStr.Remove(newStr.Length - 1);
            }
            return newStr;

        }

也可:

public string UnitMoreSpan(string str)
        {
            Regex replaceSpace = new Regex(@"\s{1,}", RegexOptions.IgnoreCase);
            return replaceSpace.Replace(str, " ").Trim();
        }