String.Substring String.Substring String.Substring String.Substring Method

定義

從這個執行個體擷取子字串。Retrieves a substring from this instance.

這個成員是多載的。This member is overloaded. 如需這個成員的完整資訊,包含語法、使用方式和範例,請按一下多載清單中的名稱。For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

多載

Substring(Index) Substring(Index) Substring(Index) Substring(Index)
Substring(Int32) Substring(Int32) Substring(Int32) Substring(Int32)

從這個執行個體擷取子字串。Retrieves a substring from this instance. 子字串會在指定的字元位置開始並繼續到字串的結尾。The substring starts at a specified character position and continues to the end of the string.

Substring(Range) Substring(Range) Substring(Range)
Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32)

從這個執行個體擷取子字串。Retrieves a substring from this instance. 子字串起始於指定的字元位置,並且具有指定的長度。The substring starts at a specified character position and has a specified length.

Substring(Index) Substring(Index) Substring(Index) Substring(Index)

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

參數

startIndex
Index Index Index Index

傳回

Substring(Int32) Substring(Int32) Substring(Int32) Substring(Int32)

從這個執行個體擷取子字串。Retrieves a substring from this instance. 子字串會在指定的字元位置開始並繼續到字串的結尾。The substring starts at a specified character position and continues to the end of the string.

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 Int32 Int32 Int32

這個執行個體中子字串之以零為起始的起始字元位置。The zero-based starting character position of a substring in this instance.

傳回

與這個執行個體中從 startIndex 開始之子字串相等的字串;如果 Empty 等於這個執行個體的長度,則為 startIndexA string that is equivalent to the substring that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance.

例外狀況

startIndex 小於零或大於此執行個體的長度。startIndex is less than zero or greater than the length of this instance.

範例

下列範例示範如何取得從字串的子字串。The following example demonstrates obtaining a substring from a string.

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
using System;

public class SubStringTest {
    public static void Main() {
        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
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方法,以不同的以等號分隔的索引鍵/值配對 ("=") 字元。The following example uses the Substring method to separate key/value pairs that are delimited by an equals ("=") character.

using System;

public class Example
{
   public static void Main()
   {
      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'
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方法用來取得的等號字元的字串中的位置。The IndexOf method is used to get the position of the equals character in the string. 若要在呼叫Substring(Int32, Int32)方法會擷取金鑰的名稱,從字串中的第一個字元開始,並擴充的呼叫所傳回的字元數IndexOf方法。The call to the Substring(Int32, Int32) method extracts the key name, which starts from the first character in the string and extends for the number of characters returned by the call to the IndexOf method. 若要呼叫Substring(Int32)方法則會擷取指派給索引鍵的值。The call to the Substring(Int32) method then extracts the value assigned to the key. 它等於字元之外的一個字元位置開始,並延伸至字串結尾。It starts at one character position beyond the equals character and extends to the end of the string.

備註

您呼叫Substring(Int32)從指定的字元位置開始,並在字串結尾結束的字串擷取子字串的方法。You call the Substring(Int32) method to extract a substring from a string that begins at a specified character position and ends at the end of the string. 起始字元位置以零為起始的;換句話說,在字串中的第一個字元位於索引 0,索引 1。The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. 若要擷取指定的字元位置開始,並結束字串的結尾之前,請呼叫Substring(Int32, Int32)方法。To extract a substring that begins at a specified character position and ends before the end of the string, call the Substring(Int32, Int32) method.

注意

這個方法不會修改目前的執行個體的值。This method does not modify the value of the current instance. 相反地,它會傳回新的字串起始於startIndex目前字串中的位置。Instead, it returns a new string that begins at the startIndex position in the current string.

若要擷取特定字元或字元序列的開頭的子字串,呼叫方法這類IndexOf或是IndexOf若要取得的值startIndexTo extract a substring that begins with a particular character or character sequence, call a method such as IndexOf or IndexOf to get the value of startIndex. 第二個範例說明這方面它會擷取金鑰的值之後的"="的字元開始一個字元位置。The second example illustrates this; it extracts a key value that begins one character position after the "=" character.

如果startIndex等於零,則方法會傳回原封不動的原始字串。If startIndex is equal to zero, the method returns the original string unchanged.

另請參閱

Substring(Range) Substring(Range) Substring(Range)

public:
 System::String ^ Substring(Range range);
public string Substring (Range range);
member this.Substring : Range -> string

參數

傳回

Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32) Substring(Int32, Int32)

從這個執行個體擷取子字串。Retrieves a substring from this instance. 子字串起始於指定的字元位置,並且具有指定的長度。The substring starts at a specified character position and has a specified length.

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 Int32 Int32 Int32

這個執行個體中子字串之以零為起始的起始字元位置。The zero-based starting character position of a substring in this instance.

length
Int32 Int32 Int32 Int32

子字串中的字元數。The number of characters in the substring.

傳回

與長度為 length 且在這個執行個體中從 startIndex 開始之子字串相等的字串;如果 Empty 等於這個執行個體的長度且 startIndex 為零,則為 lengthA string that is equivalent to the substring of length length that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance and length is zero.

例外狀況

startIndex 加上 length 表示不在此執行個體中的位置。startIndex plus length indicates a position not within this instance.

-或--or- startIndexlength 小於零。startIndex or length is less than zero.

範例

下列範例說明的簡單呼叫Substring(Int32, Int32)從第六個字元位置開始的字串擷取兩個字元的方法 (也就是在索引 5)。The following example illustrates a simple call to the Substring(Int32, Int32) method that extracts two characters from a string starting at the sixth character position (that is, at index five).

using System;

public class Example
{
   public static void Main()
   {
      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
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)在下列三種情況下,隔離在字串內的子字串的方法。The following example uses the Substring(Int32, Int32) method in the following three cases to isolate substrings within a string. 在兩個情況下的子字串會用來比較,並在第三個情況下會擲回例外狀況因為無效的參數會指定。In two cases the substrings are used in comparisons, and in the third case an exception is thrown because invalid parameters are specified.

  • 它會擷取單一字元和字串 (位於索引 2) 中的第三個位置,並比較它與"c"。It extracts the single character and the third position in the string (at index 2) and compares it with a "c". 此比較傳回trueThis comparison returns true.

  • 它會擷取第四個位置中 (位於索引 3) 的字串開始的零個字元,並將它傳遞給IsNullOrEmpty方法。It extracts zero characters starting at the fourth position in the string (at index 3) and passes it to the IsNullOrEmpty method. 這個傳回 true,因為呼叫Substring方法會傳回String.EmptyThis returns true because the call to the Substring method returns String.Empty.

  • 它會嘗試擷取一個字元在字串中第四個位置開始。It attempts to extract one character starting at the fourth position in the string. 因為在該位置沒有任何字元,方法呼叫會擲回ArgumentOutOfRangeException例外狀況。Because there is no character at that position, the method call throws an ArgumentOutOfRangeException exception.

using System;

public class Sample
{
   public static void Main() {
      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
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方法,以不同的以等號分隔的索引鍵/值配對 ("=") 字元。The following example uses the Substring method to separate key/value pairs that are delimited by an equals ("=") character.

using System;

public class Example
{
   public static void Main()
   {
      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'
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方法用來取得的等號字元的字串中的位置。The IndexOf method is used to get the position of the equals character in the string. 若要在呼叫Substring(Int32, Int32)方法會擷取金鑰的名稱,從字串中的第一個字元開始,並擴充的呼叫所傳回的字元數IndexOf方法。The call to the Substring(Int32, Int32) method extracts the key name, which starts from the first character in the string and extends for the number of characters returned by the call to the IndexOf method. 若要呼叫Substring(Int32)方法則會擷取指派給索引鍵的值。The call to the Substring(Int32) method then extracts the value assigned to the key. 它等於字元之外的一個字元位置開始,並延伸至字串結尾。It starts at one character position beyond the equals character and extends to the end of the string.

備註

您呼叫Substring(Int32, Int32)方法,可從指定的字元位置開始和結束的字串結尾之前的字串擷取子字串。You call the Substring(Int32, Int32) method to extract a substring from a string that begins at a specified character position and ends before the end of the string. 起始字元位置以零為起始的;換句話說,在字串中的第一個字元位於索引 0,索引 1。The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. 若要擷取指定的字元位置開始,並以字串的結尾會繼續,請呼叫Substring(Int32)方法。To extract a substring that begins at a specified character position and continues to the end of the string, call the Substring(Int32) method.

注意

這個方法不會修改目前的執行個體的值。This method does not modify the value of the current instance. 相反地,它會傳回新字串與字串length字元從startIndex目前字串中的位置。Instead, it returns a new string with length characters starting from the startIndex position in the current string.

length參數代表要從目前的字串執行個體中擷取的字元總數。The length parameter represents the total number of characters to extract from the current string instance. 這包括起始的字元索引,請參閱startIndexThis includes the starting character found at index startIndex. 亦即Substring方法會嘗試從索引擷取字元startIndex至索引startIndex + length -1。In other words, the Substring method attempts to extract characters from index startIndex to index startIndex + length - 1.

若要擷取特定字元或字元序列的開頭的子字串,呼叫方法這類IndexOf或是LastIndexOf若要取得的值startIndexTo extract a substring that begins with a particular character or character sequence, call a method such as IndexOf or LastIndexOf to get the value of startIndex.

如果從子字串延伸startIndex在指定的字元順序,您可以呼叫方法例如IndexOfLastIndexOf取得結束的字元或字元序列的索引。If the substring extends from startIndex to a specified character sequence, you can call a method such as IndexOf or LastIndexOf to get the index of the ending character or character sequence. 您可以接著將該值轉換成字串中的索引位置,如下所示:You can then convert that value to an index position in the string as follows:

  • 如果您搜尋過的單一字元,是要標記的子字串的結尾length參數等於endIndex - startIndex + 1,其中endIndex是傳回的值IndexOfIndexOf方法。If you've searched for a single character that is to mark the end of the substring, the length parameter equals endIndex - startIndex + 1, where endIndex is the return value of the IndexOf or IndexOf method. 下列範例會從字串擷取"b"字元的連續的區塊。The following example extracts a continuous block of "b" characters from a string.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          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
    
    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,其中endIndex的傳回值IndexOf或是IndexOf方法,和endMatchLength標記的子字串結尾的字元序列的長度。If you've searched for multiple characters that are to mark the end of the substring, the length parameter equals endIndex + endMatchLength - startIndex, where endIndex is the return value of the IndexOf or IndexOf method, and endMatchLength is the length of the character sequence that marks the end of the substring. 下列範例會擷取包含 XML 的文字區塊<definition>項目。The following example extracts a block of text that contains an XML <definition> element.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          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>
    
    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,其中endIndex是傳回的值IndexOfIndexOf方法。If the character or character sequence is not included in the end of the substring, the length parameter equals endIndex - startIndex, where endIndex is the return value of the IndexOf or IndexOf method.

如果startIndex等於零且等於目前的字串,該方法的長度會傳回未變更的原始字串。If startIndex is equal to zero and equals the length of the current string, the method returns the original string unchanged.

另請參閱

適用於