c# 字符串去掉两端空格,并且将字符串中多个空格替换成一个空格

时间:2023-12-10 19:34:26

字符串去掉两端空格,并且将字符串中多个空格替换成一个空格:

主要还是考察使用字符串的方法:

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