String.Substring メソッド

定義

このインスタンスから部分文字列を取得します。

このメンバーはオーバーロードされます。 構文、使用法、例など、このメンバーに関する完全な情報については、オーバーロードリストの名前をクリックします。

オーバーロード

名前 説明
Substring(Int32)

このインスタンスから部分文字列を取得します。 部分文字列は、指定した文字位置から始まり、文字列の末尾まで続きます。

Substring(Int32, Int32)

このインスタンスから部分文字列を取得します。 部分文字列は、指定した文字位置から始まり、長さが指定されています。

Substring(Int32)

このインスタンスから部分文字列を取得します。 部分文字列は、指定した文字位置から始まり、文字列の末尾まで続きます。

public:
 System::String ^ Substring(int startIndex);
public string Substring(int startIndex);
member this.Substring : int -> string
Public Function Substring (startIndex As Integer) As String

パラメーター

startIndex
Int32

このインスタンス内の部分文字列の 0 から始まる開始文字の位置。

返品

このインスタンス内のstartIndexで始まる部分文字列に相当する文字列。startIndexがこのインスタンスの長さと等しい場合はEmpty

例外

startIndex が 0 より小さいか、このインスタンスの長さを超えています。

次の例は、文字列から部分文字列を取得する方法を示しています。

string [] info = { "Name: Felica Walker", "Title: Mz.", 
                   "Age: 47", "Location: Paris", "Gender: F"};
int found = 0;

Console.WriteLine("The initial values in the array are:");
foreach (string s in info)
    Console.WriteLine(s);

Console.WriteLine("\nWe want to retrieve only the key information. That is:");        
foreach (string s in info) 
{
    found = s.IndexOf(": ");
    Console.WriteLine("   {0}", s.Substring(found + 2));
}

// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//       
//       We want to retrieve only the key information. That is:
//          Felica Walker
//          Mz.
//          47
//          Paris
//          F
let info = 
    [| "Name: Felica Walker"; "Title: Mz."
       "Age: 47"; "Location: Paris"; "Gender: F" |]

printfn "The initial values in the array are:"
for s in info do
    printfn $"{s}"

printfn "\nWe want to retrieve only the key information. That is:"
for s in info do
    let found = s.IndexOf ": "
    printfn $"   {s.Substring(found + 2)}"

// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//
//       We want to retrieve only the key information. That is:
//          Felica Walker
//          Mz.
//          47
//          Paris
//          F
Public Class SubStringTest
    Public Shared Sub Main()
        Dim info As String() = { "Name: Felica Walker", "Title: Mz.", 
                                 "Age: 47", "Location: Paris", "Gender: F"}
        Dim found As Integer = 0
       
        Console.WriteLine("The initial values in the array are:")
        For Each s As String In info
            Console.WriteLine(s)
        Next s

        Console.WriteLine(vbCrLf + "We want to retrieve only the key information. That is:")
        For Each s As String In info
            found = s.IndexOf(": ")
            Console.WriteLine("   {0}", s.Substring(found + 2))
        Next s
    End Sub 
End Class 
' The example displays the following output:
'       The initial values in the array are:
'       Name: Felica Walker
'       Title: Mz.
'       Age: 47
'       Location: Paris
'       Gender: F
'       
'       We want to retrieve only the key information. That is:
'          Felica Walker
'          Mz.
'          47
'          Paris
'          F

次の例では、 Substring メソッドを使用して、等号 (=) 文字で区切られたキーと値のペアを分離します。

String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
                 "Title=Code Repository" };
foreach (var pair in pairs) 
{
    int position = pair.IndexOf("=");
    if (position < 0)
        continue;
    Console.WriteLine("Key: {0}, Value: '{1}'", 
                   pair.Substring(0, position),
                   pair.Substring(position + 1));
}                          

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
let pairs = 
    [| "Color1=red"; "Color2=green"; "Color3=blue"
       "Title=Code Repository" |]
for pair in pairs do
    let position = pair.IndexOf "="
    if position >= 0 then
        printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
Module Example
   Public Sub Main()
      Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue",
                                "Title=Code Repository" }
      For Each pair In pairs
         Dim position As Integer = pair.IndexOf("=")
         If position < 0 then Continue For
         Console.WriteLine("Key: {0}, Value: '{1}'", 
                           pair.Substring(0, position),
                           pair.Substring(position + 1))
      Next                          
   End Sub
End Module
' The example displays the following output:
'     Key: Color1, Value: 'red'
'     Key: Color2, Value: 'green'
'     Key: Color3, Value: 'blue'
'     Key: Title, Value: 'Code Repository'

IndexOfメソッドは、文字列内の等号文字の位置を取得するために使用されます。 Substring(Int32, Int32) メソッドの呼び出しは、文字列の最初の文字から始まり、IndexOf メソッドの呼び出しによって返される文字数まで拡張されるキー名を抽出します。 次に、 Substring(Int32) メソッドの呼び出しによって、キーに割り当てられた値が抽出されます。 等しい文字を超える 1 文字の位置から始まり、文字列の末尾まで拡張されます。

注釈

Substring(Int32) メソッドを呼び出して、指定した文字位置から始まり、文字列の末尾で終わる文字列から部分文字列を抽出します。 開始文字の位置は 0 から始まります。つまり、文字列の最初の文字はインデックス 1 ではなくインデックス 0 になります。 指定した文字位置から始まり、文字列の末尾の前で終わる部分文字列を抽出するには、 Substring(Int32, Int32) メソッドを呼び出します。

Note

このメソッドは、現在のインスタンスの値を変更しません。 代わりに、現在の文字列の startIndex 位置から始まる新しい文字列を返します。

特定の文字または文字シーケンスで始まる部分文字列を抽出するには、 IndexOfIndexOf などのメソッドを呼び出して、 startIndexの値を取得します。 2 番目の例はこれを示しています。 = 文字の後の 1 文字の位置を開始するキー値を抽出します。

startIndexが 0 の場合、メソッドは元の文字列を変更せずに返します。

こちらもご覧ください

適用対象

Substring(Int32, Int32)

このインスタンスから部分文字列を取得します。 部分文字列は、指定した文字位置から始まり、長さが指定されています。

public:
 System::String ^ Substring(int startIndex, int length);
public string Substring(int startIndex, int length);
member this.Substring : int * int -> string
Public Function Substring (startIndex As Integer, length As Integer) As String

パラメーター

startIndex
Int32

このインスタンス内の部分文字列の 0 から始まる開始文字の位置。

length
Int32

部分文字列内の文字数。

返品

このインスタンス内のstartIndexで始まる長さlengthの部分文字列に相当する文字列。または、startIndexがこのインスタンスの長さと等しく、lengthが 0 の場合にEmpty

例外

startIndex プラス length は、このインスタンス内にない位置を示します。

-または-

startIndex または length が 0 未満です。

次の例は、6 番目の文字位置 (つまりインデックス 5) から 2 文字を文字列から抽出する、 Substring(Int32, Int32) メソッドの簡単な呼び出しを示しています。

String value = "This is a string.";
int startIndex = 5;
int length = 2;
String substring = value.Substring(startIndex, length);
Console.WriteLine(substring);

// The example displays the following output:
//       is
let value = "This is a string."
let startIndex = 5
let length = 2
let substring = value.Substring(startIndex, length)
printfn $"{substring}"

// The example displays the following output:
//       is
Module Example
   Public Sub Main()
      Dim value As String = "This is a string."
      Dim startIndex As Integer = 5
      Dim length As Integer = 2
      Dim substring As String = value.Substring(startIndex, length)
      Console.WriteLine(substring)
   End Sub
End Module
' The example displays the following output:
'       is

次の例では、次の 3 つのケースで Substring(Int32, Int32) メソッドを使用して、文字列内の部分文字列を分離します。 2 つのケースでは、部分文字列が比較で使用され、3 番目のケースでは無効なパラメーターが指定されているために例外がスローされます。

  • 文字列の 3 番目の位置 (インデックス 2) で 1 文字を抽出し、それを "c" と比較します。 この比較では、 trueが返されます。

  • 文字列の 4 番目の位置 (インデックス 3) から始まる 0 文字を抽出し、 IsNullOrEmpty メソッドに渡します。 Substring メソッドの呼び出しでString.Emptyが返されるため、true が返されます。

  • 文字列の 4 番目の位置から 1 文字を抽出しようとします。 その位置に文字がないため、メソッド呼び出しは ArgumentOutOfRangeException 例外をスローします。

string myString = "abc";
bool test1 = myString.Substring(2, 1).Equals("c"); // This is true.
Console.WriteLine(test1);
bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true.
Console.WriteLine(test2);
try
{
   string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
   Console.WriteLine(str3);
}
catch (ArgumentOutOfRangeException e)
{
   Console.WriteLine(e.Message);
}

// The example displays the following output:
//       True
//       True
//       Index and length must refer to a location within the string.
//       Parameter name: length
let myString = "abc"
let test1 = myString.Substring(2, 1).Equals "c" // This is true.
printfn $"{test1}"
let test2 = String.IsNullOrEmpty(myString.Substring(3, 0)) // This is true.
printfn $"{test2}"
try
    let str3 = myString.Substring(3, 1) // This throws ArgumentOutOfRangeException.
    printfn $"{str3}"
with :? ArgumentOutOfRangeException as e ->
    printfn $"{e.Message}"

// The example displays the following output:
//       True
//       True
//       Index and length must refer to a location within the string.
//       Parameter name: length
Public Class Sample
   Public Shared Sub Main()
      Dim myString As String = "abc"
      Dim test1 As Boolean = myString.Substring(2, 1).Equals("c") ' This is true.
      Console.WriteLine(test1)
      Dim test2 As Boolean = String.IsNullOrEmpty(myString.Substring(3, 0)) ' This is true.
      Console.WriteLine(test2)
      Try  
         Dim str3 As String = myString.Substring(3, 1) ' This throws ArgumentOutOfRangeException.
         Console.WriteLine(str3)
      Catch e As ArgumentOutOfRangeException
         Console.WriteLIne(e.Message)
      End Try   
   End Sub
End Class 
' The example displays the following output:
'       True
'       True
'       Index and length must refer to a location within the string.
'       Parameter name: length

次の例では、 Substring メソッドを使用して、等号 (=) 文字で区切られたキーと値のペアを分離します。

String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
                 "Title=Code Repository" };
foreach (var pair in pairs) 
{
    int position = pair.IndexOf("=");
    if (position < 0)
        continue;
    Console.WriteLine("Key: {0}, Value: '{1}'", 
                   pair.Substring(0, position),
                   pair.Substring(position + 1));
}                          

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
let pairs = 
    [| "Color1=red"; "Color2=green"; "Color3=blue"
       "Title=Code Repository" |]
for pair in pairs do
    let position = pair.IndexOf "="
    if position >= 0 then
        printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
Module Example
   Public Sub Main()
      Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue",
                                "Title=Code Repository" }
      For Each pair In pairs
         Dim position As Integer = pair.IndexOf("=")
         If position < 0 then Continue For
         Console.WriteLine("Key: {0}, Value: '{1}'", 
                           pair.Substring(0, position),
                           pair.Substring(position + 1))
      Next                          
   End Sub
End Module
' The example displays the following output:
'     Key: Color1, Value: 'red'
'     Key: Color2, Value: 'green'
'     Key: Color3, Value: 'blue'
'     Key: Title, Value: 'Code Repository'

IndexOfメソッドは、文字列内の等号文字の位置を取得するために使用されます。 Substring(Int32, Int32) メソッドの呼び出しは、文字列の最初の文字から始まり、IndexOf メソッドの呼び出しによって返される文字数まで拡張されるキー名を抽出します。 次に、 Substring(Int32) メソッドの呼び出しによって、キーに割り当てられた値が抽出されます。 等しい文字を超える 1 文字の位置から始まり、文字列の末尾まで拡張されます。

注釈

Substring(Int32, Int32) メソッドを呼び出して、指定した文字位置から始まり、文字列の末尾の前で終わる文字列から部分文字列を抽出します。 開始文字の位置は 0 から始まります。つまり、文字列の最初の文字はインデックス 1 ではなくインデックス 0 になります。 指定した文字位置から始まり、文字列の末尾まで続く部分文字列を抽出するには、 Substring(Int32) メソッドを呼び出します。

Note

このメソッドは、現在のインスタンスの値を変更しません。 代わりに、現在の文字列のstartIndex位置から始まるlength文字を持つ新しい文字列を返します。

length パラメーターは、現在の文字列インスタンスから抽出する文字数の合計を表します。 これには、インデックス startIndexで見つかった開始文字が含まれます。 つまり、 Substring メソッドは、インデックス startIndex からインデックス startIndex + length - 1 に文字を抽出しようとします。

特定の文字または文字シーケンスで始まる部分文字列を抽出するには、 IndexOfLastIndexOf などのメソッドを呼び出して、 startIndexの値を取得します。

部分文字列を startIndex から指定した文字シーケンスまで拡張する必要がある場合は、 IndexOfLastIndexOf などのメソッドを呼び出して、終了文字または文字シーケンスのインデックスを取得できます。 その後、次のように、その値を文字列内のインデックス位置に変換できます。

  • 部分文字列の末尾をマークする 1 文字を検索した場合、 length パラメーターは endIndex - startIndex + 1 になります。ここで、 endIndexIndexOf または LastIndexOf メソッドの戻り値です。 次の例では、文字列から "b" 文字の連続ブロックを抽出します。

    String s = "aaaaabbbcccccccdd";
    Char charRange = 'b';
    int startIndex = s.IndexOf(charRange);
    int endIndex = s.LastIndexOf(charRange);
    int length = endIndex - startIndex + 1;
    Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                    s, startIndex, length, 
                    s.Substring(startIndex, length));
    
    // The example displays the following output:
    //       aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
    let s = "aaaaabbbcccccccdd"
    let charRange = 'b'
    let startIndex = s.IndexOf charRange
    let endIndex = s.LastIndexOf charRange
    let length = endIndex - startIndex + 1
    printfn $"{s}.Substring({startIndex}, {length}) = {s.Substring(startIndex, length)}"
    
    // The example displays the following output:
    //       aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
    Module Example
       Public Sub Main()
          Dim s As String = "aaaaabbbcccccccdd"
          Dim charRange As Char = "b"c
          Dim startIndex As Integer = s.Indexof(charRange)
          Dim endIndex As Integer = s.LastIndexOf(charRange)
          Dim length = endIndex - startIndex + 1
          Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                            s, startIndex, length, 
                            s.Substring(startIndex, length))
       End Sub
    End Module
    ' The example displays the following output:
    '     aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
  • 部分文字列の末尾をマークする複数の文字を検索した場合、 length パラメーターは endIndex + endMatchLength - startIndex と等しくなります。ここで、 endIndexIndexOf または LastIndexOf メソッドの戻り値であり、 endMatchLength は部分文字列の末尾をマークする文字シーケンスの長さです。 次の例では、XML <definition> 要素を含むテキスト ブロックを抽出します。

    String s = "<term>extant<definition>still in existence</definition></term>";
    String searchString = "<definition>";
    int startIndex = s.IndexOf(searchString);
    searchString = "</" + searchString.Substring(1);
    int endIndex = s.IndexOf(searchString);
    String substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex);
    Console.WriteLine("Original string: {0}", s);
    Console.WriteLine("Substring;       {0}", substring); 
    
    // The example displays the following output:
    //     Original string: <term>extant<definition>still in existence</definition></term>
    //     Substring;       <definition>still in existence</definition>
    
    let s = "<term>extant<definition>still in existence</definition></term>"
    let searchString = "<definition>"
    let startIndex = s.IndexOf(searchString)
    let searchString = "</" + searchString.Substring 1
    let endIndex = s.IndexOf searchString
    let substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex)
    printfn $"Original string: {s}"
    printfn $"Substring;       {substring}"
    
    // The example displays the following output:
    //     Original string: <term>extant<definition>still in existence</definition></term>
    //     Substring;       <definition>still in existence</definition>
    
    Module Example
       Public Sub Main()
          Dim s As String = "<term>extant<definition>still in existence</definition></term>"
          Dim searchString As String = "<definition>"
          Dim startindex As Integer = s.IndexOf(searchString)
          searchString = "</" + searchString.Substring(1)
          Dim endIndex As Integer = s.IndexOf(searchString)
          Dim substring As String = s.Substring(startIndex, endIndex + searchString.Length - StartIndex)
          Console.WriteLine("Original string: {0}", s)
          Console.WriteLine("Substring;       {0}", substring) 
       End Sub
    End Module
    ' The example displays the following output:
    '   Original string: <term>extant<definition>still in existence</definition></term>
    '   Substring;       <definition>still in existence</definition>
    
  • 文字または文字シーケンスが部分文字列の末尾に含まれていない場合、 length パラメーターは endIndex - startIndex と等しくなります。ここで、 endIndexIndexOf または LastIndexOf メソッドの戻り値です。

startIndexが 0 に等しく、length現在の文字列の長さが等しい場合、メソッドは元の文字列を変更せずに返します。

こちらもご覧ください

適用対象