天天看点

去掉字符串多余空格

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

using System.Xml;

using System.Text.RegularExpressions;

namespace ConsoleApplication1

{

    class Class1

    {       

        static void Main(string[] args)

        {         

            Class1 myclas = new Class1();

            string str = "a b   bc";//a至b之间空格有1个,b至bc之间空格有3个。       

            Console.WriteLine("{0}", myclas.F(str ));          

            Console.ReadLine();

        }

        public string F(string originStr)

        {

            string newStr = "";

            //以空格为标志分割字符串;经测试splits长度为5,元素为:a,b,"","",bc.第3、4个元素是不为空的元素。

            string[] splits = Regex.Split(originStr, " ", RegexOptions.IgnoreCase);

            int n = splits.Length;

            for (int i = 0; i < splits.Length; i++)

            {

                if (splits[i].Trim().Equals(""))  //这里不是空格,把元素为""的过滤掉.

                {

                    continue;

                }

                else

                {

                    newStr += splits[i] + " ";  //这里加一个空格

                }

            }

            return newStr;

        }              

    }

}