Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.
To achieve this, we use the Substring() method like this:
string.Substring(startIndex, length);
This is called slicing a string. It returns the substring of length characters, starting at startIndex.
Here is an example:
string language = "JavaScript";
string substring = language.Substring(2, 6);
Console.WriteLine(substring); // Output: "vaScri"
Console.WriteLine(language); // Output: "JavaScript"
The startIndex is a zero-based index at which we start extraction and the length is the number of characters to extract.
The substring ends right before index startIndex + length. You can see in our example that the character at index 2 (v) was included, 6 characters were taken (indexes 2 to 7), and the character at index 8 (p) was excluded.
Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.
If you omit the length, Substring() extracts to the end of the string:
string language = "JavaScript";
string substring = language.Substring(4);
Console.WriteLine(substring); // Output: "Script"
Assignment
Follow the Coding Tutorial and let's slice some strings!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
