String.TrimStart 方法

定义

重载

TrimStart(Char[])

从当前字符串删除数组中指定的一组字符的所有前导匹配项。

TrimStart(Char)

删除当前字符串中的指定字符的所有前导匹配项。

TrimStart()

从当前字符串删除所有前导空白字符。

TrimStart(Char[])

从当前字符串删除数组中指定的一组字符的所有前导匹配项。

public:
 System::String ^ TrimStart(... cli::array <char> ^ trimChars);
public string TrimStart (params char[] trimChars);
public string TrimStart (params char[]? trimChars);
member this.TrimStart : char[] -> string
Public Function TrimStart (ParamArray trimChars As Char()) As String

参数

trimChars
Char[]

要删除的 Unicode 字符的数组,或 null

返回

String

从当前字符串的开头移除所出现的所有 trimChars 参数中的字符后剩余的字符串。 如果 trimCharsnull 或空数组,则改为移除空白字符。 如果从当前实例无法删除字符,此方法返回未更改的当前实例。

示例

以下示例演示了方法的基本功能 TrimStart

// TrimStart examples
string lineWithLeadingSpaces = "   Hello World!";
string lineWithLeadingSymbols = "$$$$Hello World!";
string lineWithLeadingUnderscores = "_____Hello World!";
string lineWithLeadingLetters = "xxxxHello World!";
string lineAfterTrimStart = string.Empty;

// Make it easy to print out and work with all of the examples
string[] lines = { lineWithLeadingSpaces, lineWithLeadingSymbols, lineWithLeadingUnderscores, lineWithLeadingLetters };

foreach (var line in lines)
{
    Console.WriteLine($"This line has leading characters: {line}");
}
// Output:
// This line has leading characters:    Hello World!
// This line has leading characters: $$$$Hello World!
// This line has leading characters: _____Hello World!
// This line has leading characters: xxxxHello World!

// A basic demonstration of TrimStart in action
lineAfterTrimStart = lineWithLeadingSpaces.TrimStart(' ');
Console.WriteLine($"This is the result after calling TrimStart: {lineAfterTrimStart}");
// This is the result after calling TrimStart: Hello World!   

// Since TrimStart accepts a character array of leading items to be removed as an argument,
// it's possible to do things like trim multiple pieces of data that each have different 
// leading characters,
foreach (var lineToEdit in lines)
{
    Console.WriteLine(lineToEdit.TrimStart(' ', '$', '_', 'x'));
}
// Result for each: Hello World!

// or handle pieces of data that have multiple kinds of leading characters 
var lineToBeTrimmed = "__###__ John Smith";
lineAfterTrimStart = lineToBeTrimmed.TrimStart('_', '#', ' ');
Console.WriteLine(lineAfterTrimStart);
// Result: John Smith
// TrimStart examples
let lineWithLeadingSpaces = "   Hello World!"
let lineWithLeadingSymbols = "$$$$Hello World!"
let lineWithLeadingUnderscores = "_____Hello World!"
let lineWithLeadingLetters = "xxxxHello World!"

// Make it easy to print out and work with all of the examples
let lines = [| lineWithLeadingSpaces; lineWithLeadingSymbols; lineWithLeadingUnderscores; lineWithLeadingLetters |]

for line in lines do
    printfn $"This line has leading characters: {line}"
// Output:
// This line has leading characters:    Hello World!
// This line has leading characters: $$$$Hello World!
// This line has leading characters: _____Hello World!
// This line has leading characters: xxxxHello World!

// A basic demonstration of TrimStart in action
let lineAfterTrimStart = lineWithLeadingSpaces.TrimStart ' '
printfn $"This is the result after calling TrimStart: {lineAfterTrimStart}"
// This is the result after calling TrimStart: Hello World!   

// Since TrimStart accepts a character array of leading items to be removed as an argument,
// it's possible to do things like trim multiple pieces of data that each have different 
// leading characters,
for lineToEdit in lines do
    printfn $"""{lineToEdit.TrimStart(' ', '$', '_', 'x')}"""
// Result for each: Hello World!

// or handle pieces of data that have multiple kinds of leading characters 
let lineToBeTrimmed = "__###__ John Smith"
let lineAfterTrimStart2 = lineToBeTrimmed.TrimStart('_', '#', ' ')
printfn $"{lineAfterTrimStart2}"
// Result: John Smith
Public Sub Main()
   ' TrimStart Examples
   Dim lineWithLeadingSpaces as String = "   Hello World!"
   Dim lineWithLeadingSymbols as String = "$$$$Hello World!"
   Dim lineWithLeadingUnderscores as String = "_____Hello World!"
   Dim lineWithLeadingLetters as String = "xxxxHello World!"
   Dim lineAfterTrimStart = String.Empty

   ' Make it easy to print out and work with all of the examples
   Dim lines As String() = { lineWithLeadingSpaces, line lineWithLeadingSymbols, lineWithLeadingUnderscores, lineWithLeadingLetters }

   For Each line As String in lines
     Console.WriteLine($"This line has leading characters: {line}")
   Next
   ' Output:
   ' This line has leading characters:    Hello World!
   ' This line has leading characters: $$$$Hello World!
   ' This line has leading characters: _____Hello World!
   ' This line has leading characters: xxxxHello World!

   Console.WriteLine($"This line has leading spaces: {lineWithLeadingSpaces}")
   ' This line has leading spaces:   Hello World!

   ' A basic demonstration of TrimStart in action
   lineAfterTrimStart = lineWithLeadingSpaces.TrimStart(" "c)
   Console.WriteLine($"This is the result after calling TrimStart: {lineAfterTrimStart}")
   ' This is the result after calling TrimStart: Hello World!

   ' Since TrimStart accepts a character array of leading items to be removed as an argument,
   ' it's possible to do things like trim multiple pieces of data that each have different 
   ' leading characters,
   For Each lineToEdit As String in lines
     Console.WriteLine(lineToEdit.TrimStart(" "c, "$"c, "_"c, "x"c ))
   Next
   ' Result for each: Hello World!

   ' or handle pieces of data that have multiple kinds of leading characters
   Dim lineToBeTrimmed as String = "__###__ John Smith"
   lineAfterTrimStart = lineToBeTrimmed.TrimStart("_"c , "#"c , " "c)
   Console.WriteLine(lineAfterTrimStart)
   ' Result: John Smith

 End Sub

以下示例使用此方法 TrimStart 从源代码行中剪裁空格和注释字符。 该方法StripComments包装调用TrimStart并传递包含空格和注释字符的字符数组,该数组是Visual Basic) 的撇号 () ,C# 或 F# 中的斜杠 (/) 。 TrimStart在评估字符串是否为注释时,还会调用该方法来删除前导空格。

public static string[] StripComments(string[] lines)
{
    List<string> lineList = new List<string>();
    foreach (string line in lines)
    {
        if (line.TrimStart(' ').StartsWith("//"))
            lineList.Add(line.TrimStart(' ', '/'));
    }
    return lineList.ToArray();
}
let stripComments (lines: #seq<string>) =
    [|  for line in lines do
            if line.TrimStart(' ').StartsWith "//" then
                line.TrimStart(' ', '/') |]
Public Shared Function StripComments(lines() As String) As String()
   Dim lineList As New List(Of String)
   For Each line As String In lines
      If line.TrimStart(" "c).StartsWith("'") Then
         linelist.Add(line.TrimStart("'"c, " "c))
      End If
   Next
   Return lineList.ToArray()
End Function

下面的示例演示对 StripComments 方法的调用。

public static void Main()
{
    string[] lines = {"using System;",
                   "",
                   "public class HelloWorld",
                   "{",
                   "   public static void Main()",
                   "   {",
                   "      // This code displays a simple greeting",
                   "      // to the console.",
                   "      Console.WriteLine(\"Hello, World.\");",
                   "   }",
                   "}"};
    Console.WriteLine("Before call to StripComments:");
    foreach (string line in lines)
        Console.WriteLine("   {0}", line);

    string[] strippedLines = StripComments(lines);
    Console.WriteLine("After call to StripComments:");
    foreach (string line in strippedLines)
        Console.WriteLine("   {0}", line);
}
// This code produces the following output to the console:
//    Before call to StripComments:
//       using System;
//   
//       public class HelloWorld
//       {
//           public static void Main()
//           {
//               // This code displays a simple greeting
//               // to the console.
//               Console.WriteLine("Hello, World.");
//           }
//       }  
//    After call to StripComments:
//       This code displays a simple greeting
//       to the console.
let lines = 
    [| "module HelloWorld"
       ""
       "[<EntryPoint>]"
       "let main _ ="
       "    // This code displays a simple greeting"
       "    // to the console."
       "    printfn \"Hello, World.\""
       "    0" |]
printfn "Before call to StripComments:"
for line in lines do
    printfn $"   {line}"

let strippedLines = stripComments lines
printfn "After call to StripComments:"
for line in strippedLines do
    printfn $"   {line}"
// This code produces the following output to the console:
//    Before call to StripComments:
//       module HelloWorld
//
//       [<EntryPoint>]
//       let main _ =
//           // This code displays a simple greeting
//           // to the console.
//           printfn "Hello, World."
//           0
//    After call to StripComments:
//       This code displays a simple greeting
//       to the console.
Public Shared Sub Main()
   Dim lines() As String = {"Public Module HelloWorld", _
                            "   Public Sub Main()", _
                            "      ' This code displays a simple greeting", _
                            "      ' to the console.", _
                            "      Console.WriteLine(""Hello, World."")", _
                            "   End Sub", _
                            " End Module"}
   Console.WriteLine("Code before call to StripComments:")
   For Each line As String In lines
      Console.WriteLine("   {0}", line)                         
   Next                            
   
   Dim strippedLines() As String = StripComments(lines) 
   Console.WriteLine("Code after call to StripComments:")
   For Each line As String In strippedLines
      Console.WriteLine("   {0}", line)                         
   Next                            
End Sub
' This code produces the following output to the console:
'    Code before call to StripComments:
'       Public Module HelloWorld
'          Public Sub Main()
'             ' This code displays a simple greeting
'             ' to the console.
'             Console.WriteLine("Hello, World.")
'          End Sub
'       End Module
'    Code after call to StripComments:
'       This code displays a simple greeting
'       to the console.

注解

该方法 TrimStart(System.Char[]) 从当前字符串中删除参数中的所有 trimChars 前导字符。 当遇到未加入 trimChars 字符时,剪裁操作将停止。 例如,如果当前字符串为“123abc456xyz789”,并且 trimChars 包含“1”到“9”的数字,该方法 TrimStart(System.Char[]) 将返回“abc456xyz789”。

备注

TrimStart(System.Char[])如果该方法从当前实例中删除任何字符,则此方法不会修改当前实例的值。 而是返回一个新字符串,在该字符串中 trimChars ,将删除当前实例中找到的参数中的所有前导字符。

调用方说明

.NET Framework 3.5 SP1 和早期版本维护此方法剪裁的空白字符的内部列表(如果trimCharsnull或空数组)。 从 .NET Framework 4 开始(如果trimCharsnull或空数组)开始,该方法会剪裁所有 Unicode 空格字符 (,即在将返回值传递到IsWhiteSpace(Char)方法) 时生成true返回值的字符。 由于此更改,Trim().NET Framework 3.5 SP1 和早期版本中的方法删除了两个字符,零宽度空格 (U+200B) 和零宽度 NO-BREAK SPACE (U+FEFF) ,.NET Framework Trim() 4 及更高版本中的方法不会删除。 此外,Trim().NET Framework 3.5 SP1 和早期版本中的方法不会剪裁三个 Unicode 空格字符:蒙古文 VOWEL 分隔符 (U+180E) 、窄无中断空间 (U+202F) ,以及中等数学空间 (U+205F) 。

另请参阅

适用于

TrimStart(Char)

删除当前字符串中的指定字符的所有前导匹配项。

public:
 System::String ^ TrimStart(char trimChar);
public string TrimStart (char trimChar);
member this.TrimStart : char -> string
Public Function TrimStart (trimChar As Char) As String

参数

trimChar
Char

要删除的 Unicode 字符。

返回

String

从当前字符串的开头删除所出现的所有 trimChar 字符后剩余的字符串。 如果从当前实例无法删除字符,此方法返回未更改的当前实例。

注解

该方法 TrimStart(System.Char) 从当前字符串中删除所有前导 trimChar 字符。 当遇到未 trimChar 遇到的字符时,剪裁操作将停止。 例如,如果 trimChar 当前 - 字符串为“---abc---xyz----”,则 TrimStart(System.Char) 该方法返回“abc---xyz----”。

备注

TrimStart(System.Char)如果该方法从当前实例中删除任何字符,则此方法不会修改当前实例的值。 而是返回一个新字符串,在该字符串中删除当前实例中找到的所有前导 trimChar 字符。

适用于

TrimStart()

从当前字符串删除所有前导空白字符。

public:
 System::String ^ TrimStart();
public string TrimStart ();
member this.TrimStart : unit -> string
Public Function TrimStart () As String

返回

String

从当前字符串的开头删除所有空白字符后剩余的字符串。 如果从当前实例无法删除字符,此方法返回未更改的当前实例。

注解

该方法 TrimStart 从当前字符串中删除所有前导空格字符。 遇到非空格字符时,剪裁操作将停止。 例如,如果当前字符串为“abc xyz”,该方法 TrimStart 将返回“abc xyz”。

备注

TrimStart如果该方法从当前实例中删除任何字符,则此方法不会修改当前实例的值。 而是返回一个新字符串,在该字符串中删除当前实例中找到的所有前导空格字符。

适用于