Wednesday, April 24, 2024 00:58

Table of contents >> Strings And Text Processing > Substring

Substring

A substring is a string located inside another string. To extract a portion of a string (substring), we can use the Substring() method, with some additional parameters, such as the starting index and the character count or length. Whenever the length parameter is omitted, the function will simply return the substring that starts at the specified index until the end of the string. Let’s take an example:

First, we declared a string called str. Then, we used the Substring() method to extract a portion of this string into another string, called substr. We specified only the starting index, 11, which means that the function will return the substring starting at the 11th index location, and because we did not specify a length, it continued until the end of the string, resulting in “Jane Doe”. In the second example, we specified the same index, but we also included a length of 4, which translated as getting the substring that starts at index 11 and continues on the next 4 characters. This resulted in “Jane”. Be aware that as with a lot of other functions, the index starts at 0, not 1.

C# Substring

We already learned in the previous lesson that IndexOf() and LastIndexOf() return a numeric index, which is the starting position of the found string. Since Substring() also takes a numeric index parameter, we can combine them:

First, IndexOf() returned the index of the first occurrence of “Jane”, which was then used by Substring() to extract the specified string. In second example, the same thing happened, but this time we used LastIndexOf() function, and we added 3 to the index it returned, because as I was saying in the previous lesson, both IndexOf() and LastIndexOf() return the index of the first character they find. In our case, since we searched for “is “, it returned the index location of “i”, so we needed to add an offset of 3 characters, to get to the end of “is “.

Tags: , , , ,

Leave a Reply



Follow the white rabbit