String.Substring メソッド

定義

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

このメンバーはオーバーロードされます。 構文、使用方法、例など、このメンバーの詳細については、オーバーロード リストで名前をクリックしてください。

オーバーロード

Substring(Int32)

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

Substring(Int32, Int32)

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

Substring(Int32)

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

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

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 未満か、またはこのインスタンスの長さを超えています。

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

using namespace System;
using namespace System::Collections;

int main()
{
   array<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:");
   for each (String^ s in info) 
      Console::WriteLine(s);

   Console::WriteLine("\nWe want to retrieve only the key information. That is:");
   for each (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
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) 呼び出します。

注意

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

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

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

こちらもご覧ください

適用対象

Substring(Int32, Int32)

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

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

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 がゼロの場合は Empty

例外

startIndexlength を加算した値はこのインスタンスの範囲外である位置を示します。

または

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

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

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

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

  • 文字列の 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) 呼び出します。

注意

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

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

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

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

  • 部分文字列の末尾をマークする 1 文字を検索した場合、lengthパラメーターは + 1 に等しくなりますendIndexstartIndex - 。ここでendIndex、 は メソッドまたは LastIndexOf メソッドのIndexOf戻り値です。 次の例では、文字列から "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 パラメーターは と等しくなります - endMatchLength + endIndexstartIndex。ここでendIndex、 は メソッドまたは LastIndexOf メソッドのIndexOf戻り値で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 パラメーターは と等しくなりますendIndexstartIndex - 。ここでendIndex、 は メソッドまたは LastIndexOf メソッドのIndexOf戻り値です。

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

こちらもご覧ください

適用対象