温馨提示×

c#字符串怎么去除空格

c#
小亿
178
2024-08-05 17:06:11
栏目: 编程语言

在C#中去除字符串中的空格有多种方法,以下是其中一些常用的方法:

  1. 使用Trim()方法去除字符串两端的空格:
string str = "   Hello World   ";
str = str.Trim();
Console.WriteLine(str); // 输出:Hello World
  1. 使用Replace()方法将空格替换为空字符串:
string str = "   Hello World   ";
str = str.Replace(" ", "");
Console.WriteLine(str); // 输出:HelloWorld
  1. 使用正则表达式去除所有空格:
using System.Text.RegularExpressions;

string str = "   Hello World   ";
str = Regex.Replace(str, @"\s", "");
Console.WriteLine(str); // 输出:HelloWorld
  1. 使用Split()方法将字符串按空格分割后再拼接:
string str = "   Hello World   ";
string[] words = str.Split(' ');
str = string.Join("", words);
Console.WriteLine(str); // 输出:HelloWorld

这些方法可以根据需要选择其中一种或组合使用。

0