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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Google+ photo

You are commenting using your Google+ 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

%d bloggers like this: