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 文字が検出されると停止します。 たとえば、 が で-、現在の文字列が "---abc---xyz----" の場合trimCharTrimStart(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 以前のバージョンでは、 が または空の配列の場合trimCharsにこのメソッドによってトリミングされる空白文字の内部リストがnull保持されます。 .NET Framework 4 以降では、 が null または空の配列の場合trimChars、メソッドはすべての Unicode 空白文字 (つまり、メソッドにIsWhiteSpace(Char)渡されたときに戻り値をtrue生成する文字) をトリミングします。 この変更により、Trim().NET Framework 3.5 SP1 以前のバージョンの メソッドは、2 文字の ZERO WIDTH SPACE (U+200B) と ZERO WIDTH NO-BREAK SPACE (U+FEFF) Trim() を削除します。この 2 文字は、.NET Framework 4 以降のバージョンのメソッドでは削除されません。 さらに、Trim().NET Framework 3.5 SP1 以前のバージョンの メソッドでは、モンゴル語の VOWEL SEPARATOR (U+180E)、NARROW NO-BREAK SPACE (U+202F)、MEDIUM MATHEMATICAL SPACE (U+205F) の 3 つの Unicode 空白文字はトリミングされません。

こちらもご覧ください

適用対象