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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-19 我要评论
想了解c#字符串去掉空格的二种方法(去掉两端空格)的相关内容吗,在本文为您仔细讲解字符串去掉空格的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:字符串去掉空格,下面大家一起来学习吧。

使用字符串的方法:

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 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们