c#字符串去掉空格的二种方法(去掉两端空格)


使用字符串的方法:

trim();去掉字符串两端空格

split();切割

string.join();连接

复制代码 代码如下:

class Program
    {
        static void Main(string[] args)
        {
            //原字符串
            string str = "  hello      world,你  好 世界   !    ";
            //去掉两端空格
           str= str.Trim();
            //以空格切割
           string [] strArray= str.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries);
            //以空格连接
           string newStr= string.Join(" ", strArray);
            Console.WriteLine(newStr);
            Console.ReadKey();
        }
    }

使用正则的方法:

复制代码 代码如下:

class Program
    {
        static void Main(string[] args)
        {
            //原字符串
            string str = "  hello      world,你  好 世界   !    ";
            string s = Regex.Replace(str, @"\s+", " ").Trim();
            Console.WriteLine(s);
            Console.ReadKey();
        }
    }


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3