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 index-based subscripting like this:
let start = string.index(string.startIndex, offsetBy: startOffset)
let end = string.index(string.startIndex, offsetBy: endOffset)
String(string[start..<end])
This is called slicing a string. It returns the substring from startIndex to endIndex.
Here is an example:
let language = "JavaScript"
let start = language.index(language.startIndex, offsetBy: 2)
let end = language.index(language.startIndex, offsetBy: 6)
let substring = String(language[start..<end])
print(substring) // Output: "vaSc"
print(language) // Output: "JavaScript"
The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.
The substring will not include the character at endIndex. You can see in our example that the character at index 2 (v) was included while the character at index 6 (r) 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 want to extract from an index to the end of the string, use an open-ended range:
let language = "JavaScript"
let start = language.index(language.startIndex, offsetBy: 4)
let substring = String(language[start...])
print(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. Premium is unlimited.