跳到主要内容

C# String Trim() 字符串修剪方法

Trim() 方法从指定的字符串中移除任何前导(起始)和尾随(结束)的空格。

示例

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text = " Ice cream ";

// 移除前导和尾随的空格
string s1 = text.Trim();

Console.WriteLine(s1);

Console.ReadLine();
}
}
}
// 输出: Ice cream

Trim() 语法

字符串 Trim() 方法的语法如下:

Trim(params char[]? trimChars)

这里,Trim()String 类的方法。

Trim() 参数

Trim() 方法接受以下参数:

  • trimChars - 要移除的字符数组

Trim() 返回值

Trim() 方法返回:

  • 移除前导和尾随空格或指定字符的字符串

注意:在编程中,空格是表示水平或垂直空间的任何字符或字符序列。例如:空格,换行符 \n,制表符 \t,垂直制表符 \v 等。

示例1:C# String Trim()

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text1 = "\n\n\n Ice\ncream \n\n";
string text2 = "\n\n\n Chocolate \n\n";

// 移除前导和尾随的空格
string s1 = text1.Trim();
Console.WriteLine(s1);

// 移除前导和尾随的空格
string s2 = text2.Trim();
Console.WriteLine(s2);

Console.ReadLine();
}
}
}

输出

Ice
cream
Chocolate

在这里,

  • text1.Trim() 返回:
Ice
cream
  • text2.Trim() 返回:
Chocolate

从上面的示例中可以看出,Trim() 方法只移除前导和尾随的空格,不会移除出现在中间的空格。

示例2:C# String Trim() - 移除字符

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

// 要移除的字符
char[] charsToTrim = {'(', ')', '^'};

string text = "(^^Everyone loves ice cream^^)";
Console.WriteLine("移除前: " + text);

// 移除前导和尾随的指定字符
string s1 = text.Trim(charsToTrim);
Console.WriteLine("移除后: " + s1);

Console.ReadLine();
}
}
}

输出

移除前: (^^Everyone loves ice cream^^)
移除后: Everyone loves ice cream

在这里,我们使用 Trim() 方法移除了前导和尾随的 '('')''^' 字符。

注意:要移除字符串中单词之间的空格或字符,必须使用正则表达式。

示例3:C# String TrimStart() 和 TrimEnd()

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text = " Everyone loves ice cream \n\n";
string result;

// 移除开始的空格
result = text.TrimStart();
Console.WriteLine(result);

// 移除结束的空格
result = text.TrimEnd();
Console.WriteLine(result);

Console.ReadLine();
}
}
}

输出

Everyone loves ice cream


Everyone loves ice cream

在这里,

  • text.TrimStart() - 移除开始的空格
  • text.TrimEnd() - 移除结束的空格