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

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方法用于获取字符串中 equals 字符的位置。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. 它从 equals 字符之外的一个字符位置开始, 并扩展到字符串的末尾。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.

若要提取以特定字符或字符序列开头的子字符串, 请调用方法 (如IndexOfIndexOf ) startIndex来获取的值。To 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.

异常

startIndexlength 指示不在此实例内的位置。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).

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. Substring方法返回 true, 因为对方法的调用String.Empty将返回。This 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.

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方法用于获取字符串中 equals 字符的位置。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. 它从 equals 字符之外的一个字符位置开始, 并扩展到字符串的末尾。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. 这包括索引startIndex处的起始字符。This includes the starting character found at index startIndex. 换言之, 此Substring方法尝试从length索引startIndex到索引startIndex + -1 提取字符。In other words, the Substring method attempts to extract characters from index startIndex to index startIndex + length - 1.

若要提取以特定字符或字符序列开头的子字符串, 请调用方法 (如IndexOfLastIndexOf ) startIndex来获取的值。To 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扩展到指定的字符序列, 则可以调用方法IndexOf (如或LastIndexOf ) 来获取结束字符或字符序列的索引。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 - IndexOf startIndex + 1, 其中endIndex是或IndexOf的返回值付款方式.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.

    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 + startIndex endMatchLength - , 其中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.

    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 - IndexOf startIndex, 其中endIndex是或IndexOf的返回值付款方式.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.

另请参阅

适用于