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