溫馨提示×

c#字符串怎么去除空格

c#
小億
182
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

這些方法可以根據(jù)需要選擇其中一種或組合使用。

0