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
3 Ways to Find Your Mobile Phone's Serial Number Without Taking it Apart
Should you invest in bitcoin? - Times Money Mentor
Overton Funeral Home Waterloo Iowa
El Paso Pet Craigslist
Greedfall Console Commands
30 Insanely Useful Websites You Probably Don't Know About
Craigslist In South Carolina - Craigslist Near You
What is IXL and How Does it Work?
Missing 2023 Showtimes Near Lucas Cinemas Albertville
Unit 1 Lesson 5 Practice Problems Answer Key
The Rise of Breckie Hill: How She Became a Social Media Star | Entertainment
Hope Swinimer Net Worth
Extra Virgin Coconut Oil Walmart
Equipamentos Hospitalares Diversos (Lote 98)
Cambridge Assessor Database
Parent Resources - Padua Franciscan High School
3S Bivy Cover 2D Gen
360 Tabc Answers
My Homework Lesson 11 Volume Of Composite Figures Answer Key
St. Petersburg, FL - Bombay. Meet Malia a Pet for Adoption - AdoptaPet.com
Is A Daytona Faster Than A Scat Pack
A Biomass Pyramid Of An Ecosystem Is Shown.Tertiary ConsumersSecondary ConsumersPrimary ConsumersProducersWhich
BMW K1600GT (2017-on) Review | Speed, Specs & Prices
Dwc Qme Database
Xsensual Portland
The Old Way Showtimes Near Regency Theatres Granada Hills
Garnish For Shrimp Taco Nyt
Caring Hearts For Canines Aberdeen Nc
Utexas Iot Wifi
Dei Ebill
Craftybase Coupon
How to Use Craigslist (with Pictures) - wikiHow
Insidious 5 Showtimes Near Cinemark Southland Center And Xd
LG UN90 65" 4K Smart UHD TV - 65UN9000AUJ | LG CA
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
Ripsi Terzian Instagram
Upstate Ny Craigslist Pets
Help with your flower delivery - Don's Florist & Gift Inc.
Chilangos Hillsborough Nj
Isabella Duan Ahn Stanford
What to Do at The 2024 Charlotte International Arts Festival | Queen City Nerve
St Vrain Schoology
Gon Deer Forum
Spurs Basketball Reference
The 13 best home gym equipment and machines of 2023
Suppress Spell Damage Poe
Diamond Spikes Worth Aj
Dmv Kiosk Bakersfield
Booked On The Bayou Houma 2023
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.