String.TrimStart 方法

定义

重载

TrimStart(ReadOnlySpan<Char>)

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

TrimStart()

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

TrimStart(Char)

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

TrimStart(Char[])

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

TrimStart(ReadOnlySpan<Char>)

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

public:
 System::String ^ TrimStart(ReadOnlySpan<char> trimChars);
public string TrimStart (scoped ReadOnlySpan<char> trimChars);
member this.TrimStart : ReadOnlySpan<char> -> string
Public Function TrimStart (trimChars As ReadOnlySpan(Of Char)) As String

参数

trimChars
ReadOnlySpan<Char>

要删除的 Unicode 字符的范围。

返回

trimChars 参数中出现的所有字符之后保留的字符串将从当前字符串的开头删除。 如果 trimChars 为空,则会删除空格字符。 如果当前实例中无法剪裁任何字符,该方法将返回当前实例不变。

适用于

TrimStart()

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

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

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

返回

从当前字符串的开头删除所有空格字符之后保留的字符串。 如果当前实例中无法剪裁任何字符,该方法将返回当前实例不变。

注解

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

注意

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

适用于

TrimStart(Char)

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

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

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 字符。

返回

trimChar 字符的所有匹配项之后保留的字符串将从当前字符串的开头删除。 如果当前实例中无法剪裁任何字符,该方法将返回当前实例不变。

注解

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

注意

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

适用于

TrimStart(Char[])

Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

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

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[]

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

返回

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 参数中的所有前导字符。

调用方说明

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

另请参阅

适用于