String.TrimStart 方法

定义

重载

TrimStart()

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

TrimStart(Char)

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

TrimStart(Char[])

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

TrimStart()

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

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)

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

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

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

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

返回

从当前字符串的开头移除所出现的所有 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) 和零宽度无中断空间 (U+FEFF) ,.NET Framework Trim() 4 及更高版本中的方法不会删除。 此外,Trim().NET Framework 3.5 SP1 及更早版本中的方法不会剪裁三个 Unicode 空格字符:MONGOLIAN VOWEL SEPARATOR (U+180E) 、NARROW NO-BREAK SPACE (U+202F) 和 MEDIUM MATHEMATICAL SPACE (U+205F) 。

另请参阅

适用于