C# String Trim()

Trim() 方法用于删除指定字符串开头(前导)和结尾(尾部)的任何空白字符。

示例

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
  
      string text = "    Ice cream   ";

// trims leading and trailing whitespaces string s1 = text.Trim();
Console.WriteLine(s1); Console.ReadLine(); } } } // Output: 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";

// trims leading and trailing whitespaces string s1 = text1.Trim();
Console.WriteLine(s1);
// trims leading and trailing whitespaces string s2 = text2.Trim();
Console.WriteLine(s2); Console.ReadLine(); } } }

输出

Ice
cream
Chocolate

这里,

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

从上面的示例可以看出,Trim() 方法只删除前导和尾部的空白字符。它不会删除出现在中间的空白字符。


示例 2:C# String Trim() - Trim Characters

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      // chars to trim
      char[] charsToTrim = {'(', ')', '^'};

      string text = "(^^Everyone loves ice cream^^)";
      Console.WriteLine("Before trim: " + text);

// trims leading and trailing specified chars string s1 = text.Trim(charsToTrim);
Console.WriteLine("After trim: " + s1); Console.ReadLine(); } } }

输出

Before trim: (^^Everyone loves ice cream^^)
After trim: 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;
      
// trims starting whitespace result = text.TrimStart();
Console.WriteLine(result);
// trims ending whitespace result = text.TrimEnd();
Console.WriteLine(result); Console.ReadLine(); } } }

输出

Everyone loves ice cream


  Everyone loves ice cream

这里,

  • text.TrimStart() - 删除开头的空白字符
  • text.TrimEnd() - 删除结尾的空白字符
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战