To remove a substring at a specified range, use the removeRange(_:) method:
1 let range = advance(welcome.endIndex, -6)..
Swift 2
We're going to use var
since removeRange
needs to operate on a mutable string.
var welcome = "hello there"
This line:
let range = welcome.endIndex.advancedBy(-6)..<welcome.endIndex
means that we start from the end of the string (welcome.endIndex
) and move back by 6 characters (advance by a negative number = move back), then ask for the range (..<
) between our position and the end of the string (welcome.endIndex
).
It creates a range of 5..<11
, which encompasses the " there" part of the string.
If you remove this range of characters from the string with:
welcome.removeRange(range)
then your string will be the remaining part:
print(welcome) // prints "hello"
You can take it the other way (from the start index of the string) for the same result:
welcome = "hello there"
let otherRange = welcome.startIndex.advancedBy(5)..<welcome.endIndex
welcome.removeRange(otherRange)
print(welcome) // prints "hello"
Here we start from the beginning of the string (welcome.startIndex
), then we advance by 5 characters, then we make a range (..<
) from here to the end of the string (welcome.endIndex
).
Note: the advance
function can work forward and backward.
Swift 3
The syntax has changed but the concepts are the same.
var welcome = "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
print(welcome) // prints "hello"
welcome = "hello there"
let otherRange = welcome.index(welcome.startIndex, offsetBy: 5)..<welcome.endIndex
welcome.removeSubrange(otherRange)
print(welcome) // prints "hello"