String.Substring Method (System) | Microsoft Learn
Maybe your like
- csharp
- vb
- fsharp
- cpp
Share via
Facebook x.com LinkedIn Email Copy Markdown PrintNote
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Summarize this article for me String.Substring MethodDefinition
Namespace: System Assemblies:mscorlib.dll, System.Runtime.dll Assemblies:netstandard.dll, System.Runtime.dll Assembly:System.Runtime.dll Assembly:mscorlib.dll Assembly:netstandard.dllImportant
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
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.
Overloads
| Name | Description |
|---|---|
| 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(Int32, Int32) | Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length. |
Substring(Int32)
Source:String.Manipulation.cs Source:String.Manipulation.cs Source:String.Manipulation.cs Source:String.Manipulation.csRetrieves 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 StringParameters
startIndex Int32The zero-based starting character position of a substring in this instance.
Returns
StringA 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.
Exceptions
ArgumentOutOfRangeExceptionstartIndex is less than zero or greater than the length of this instance.
Examples
The following example demonstrates obtaining a substring from a string.
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 ' FThe 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' 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'The IndexOf method is used to get the position of the equals character in the string. 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. 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.
Remarks
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. The starting character position is 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 ends before the end of the string, call the Substring(Int32, Int32) method.
Note
This method does not modify the value of the current instance. Instead, it returns a new string that begins at the startIndex position in the current string.
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.
If startIndex is equal to zero, the method returns the original string unchanged.
See also
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Split(Char[])
- Trim(Char[])
Applies to
Substring(Int32, Int32)
Source:String.Manipulation.cs Source:String.Manipulation.cs Source:String.Manipulation.cs Source:String.Manipulation.csRetrieves 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 StringParameters
startIndex Int32The zero-based starting character position of a substring in this instance.
length Int32The number of characters in the substring.
Returns
StringA 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.
Exceptions
ArgumentOutOfRangeExceptionstartIndex plus length indicates a position not within this instance.
-or-
startIndex or length is less than zero.
Examples
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 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: ' isThe 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.
It extracts the single character at 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 String.Empty.
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.
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' 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'The IndexOf method is used to get the position of the equals character in the string. 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. 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.
Remarks
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. The starting character position is 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(Int32) method.
Note
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 should extend 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 LastIndexOf method. 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 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) = bbbIf 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 LastIndexOf 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.
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>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 LastIndexOf method.
If startIndex is equal to zero and length equals the length of the current string, the method returns the original string unchanged.
See also
- Remove(Int32, Int32)
- Replace(Char, Char)
- Trim(Char[])
Applies to
Collaborate with us on GitHub The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide..NET
Open a documentation issue Provide product feedbackFeedback
Was this page helpful?
Yes No NoNeed help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Ask Learn Ask Learn Suggest a fix?In this article
Was this page helpful?
Yes No NoNeed help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Ask Learn Ask Learn Suggest a fix?Tag » What Is Substring In C#
-
Substring In C# - C# Corner
-
C# | Substring() Method - GeeksforGeeks
-
C# String Substring() (With Examples) - Programiz
-
C# Substring() Method - Tutorialspoint
-
How To Use C# String Substring
-
C# Substring Examples - Dot Net Perls
-
C# Substring 문자열 자르기 - 개발인생
-
How To Get A Substring From A String In C#
-
C# String SubString() Method - Javatpoint
-
082 - How To Use C# String Substring - YouTube
-
What Is Substring In C# With Example? [60 Answers Found]
-
How To Check If String Contains Specified Substring In C#?
-
Visual C# .net Strings - Substring - Home And Learn Courses
-
JavaScript String Substring() Method - W3Schools