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.

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

异常

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

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.

若要提取特定的字符或字符序列开头的子字符串,请如调用方法IndexOfLastIndexOf若要获取的值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的返回值IndexOfIndexOf方法,和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.

另请参阅

适用于