c#字符串去掉空格的二种方法(去掉两端空格)
c#字符串去掉空格的二种方法(去掉两端空格)
发布时间:2016-12-28 来源:查字典编辑
摘要:使用字符串的方法:trim();去掉字符串两端空格split();切割string.join();连接复制代码代码如下:classProgr...

使用字符串的方法:

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

}

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C#教程学习
热门C#教程学习
编程开发子分类