Anonymous user
Substring/Top and tail: Difference between revisions
→{{header|Swift}}
Line 1,089:
012345678
12345678</pre>
The other method is slicing by range subscripting:
<lang swift>let txt = "0123456789"
Line 1,107 ⟶ 1,098:
012345678
12345678</pre>
Another way is mutating the string:
<lang swift>var txt = "0123456789"
txt.removeAtIndex(txt.startIndex)
txt.removeAtIndex(txt.endIndex.predecessor())</lang>
The above functions return what they remove.
You can also extend String type and define BASIC-style functions:
<lang swift>extension String {
/// Ensure positive indexes
func index(index: Int) -> String.Index {▼
return advance( index < 0 ? self.endIndex : self.startIndex, index)▼
private func positive(index: Int) -> Int {
if index >= 0 { return index }
}
/// Unicode character by zero-based integer (character) `index`
/** Left portion of text to index */▼
/// Supports negative character index to count from end. (-1 returns character before last)
}
/// String slice by character index
subscript(range: Range<Int>) -> String {
return self[advance(startIndex, range.startIndex) ..<
advance(startIndex, range.endIndex, endIndex)]
}
func left(index : Int) -> String {
return self[0 .
}
/
func right(index : Int) -> String{
▲ return self.substringToIndex(self.index(index))
return self[positive(index) ..< count(self)]
}
/
func mid(start: Int, _ end: Int) -> String {
return self[positive(start) ..< positive(end)]
}
|