#102 – Use Substring() to Extract Substrings From A String

The String.IndexOf method searched for the location of a substring in a larger string, given the substring.  You can use the Substring method to do the reverse–extract a substring, given its position in the larger string.

 string s = "Itsy bitsy spider";
 string s2 = s.Substring(5);  // bitsy spider  (start at 6th character, extract until end of string)
 s2 = s.Substring(5, 4);      // bits
 s.Substring(2, s.Length);    // throws ArgumentOutOfRangeException

Also note that the Substring method doesn’t change the original string, but just returns the substring asked for.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers