当前位置: 移动技术网 > IT编程>开发语言>c# > c#字符串去掉空格的二种方法(去掉两端空格)

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

使用字符串的方法:

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();
        }
    }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网