String.Substring Method (System) (2024)

Table of Contents
Examples Remarks See also Applies to
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs
Source:
String.Manipulation.cs

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

Parameters

startIndex
Int32

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

length
Int32

The number of characters in the substring.

Returns

String

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.

Exceptions

ArgumentOutOfRangeException

startIndex 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 = 5let length = 2let 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 SubEnd Module' The example displays the following output:' is

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.

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

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
let myString = "abc"let test1 = myString.Substring(2, 1).Equals "c" // This is true.printfn $"{test1}"let test2 = String.IsNullOrEmpty(myString.Substring(3, 0)) // This is true.printfn $"{test2}"try let str3 = myString.Substring(3, 1) // This throws ArgumentOutOfRangeException. printfn $"{str3}"with :? ArgumentOutOfRangeException as e -> printfn $"{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 SubEnd 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.

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 SubEnd 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 charRangelet endIndex = s.LastIndexOf charRangelet length = endIndex - startIndex + 1printfn $"{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 SubEnd 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 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 1let endIndex = s.IndexOf searchStringlet 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 SubEnd 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

String.Substring Method (System) (2024)
Top Articles
Advances and Challenges in Drone Detection and Classification Techniques: A State-of-the-Art Review
What You Should Know About Gmail Encryption - Arcalea
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Tuan Roob DDS

Last Updated:

Views: 6132

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Tuan Roob DDS

Birthday: 1999-11-20

Address: Suite 592 642 Pfannerstill Island, South Keila, LA 74970-3076

Phone: +9617721773649

Job: Marketing Producer

Hobby: Skydiving, Flag Football, Knitting, Running, Lego building, Hunting, Juggling

Introduction: My name is Tuan Roob DDS, I am a friendly, good, energetic, faithful, fantastic, gentle, enchanting person who loves writing and wants to share my knowledge and understanding with you.