StringSubstring Method
 

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

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

Parameters

startIndex
Type:

The zero-based starting character position of a substring in this instance.

length
Type:

The number of characters in the substring.

Return Value

Type:

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

Exception Condition
ArgumentOutOfRangeException

startIndex plus length indicates a position not within this instance.

-or-

startIndex or length is less than zero.

You call the Substring method to extract a substring from a string that begins at a specified character position and ends before the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and continues to the end of the string, call the Substring method.

System_CAPS_noteNote

This method does not modify the value of the current instance. Instead, it returns a new string with length characters starting from the startIndex position in the current string.

The length parameter represents the total number of characters to extract from the current string instance. This includes the starting character found at index startIndex. In other words, the Substring method attempts to extract characters from index startIndex to index startIndex + length - 1.

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.

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:

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

If startIndex is equal to zero and equals the length of the current string, the method returns the original string unchanged.

The following example illustrates a simple call to the Substring 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

The following example uses the Substring 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.

  • It extracts the single character and the third position in the string (at index 2) and compares it with a "c". This comparison returns true.

  • It extracts zero characters starting at the fourth position in the string (at index 3) and passes it to the IsNullOrEmpty method. This returns true because the call to the Substring method returns StringEmpty.

  • It attempts to extract one character starting at the fourth position in the string. 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

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'

The IndexOf method is used to get the position of the equals character in the string.. The call to the Substring 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. The call to the Substring 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.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top