let str = "abcdef"
// returns "bc"
str[1 ..< 3]
// returns "f"
str[5]
// returns ""
str[80]
// returns "def"
str.substring(fromIndex: 3)
// returns "abcd"
str.substring(toIndex: str.length - 2)
//Расширение для работы String
extension String {
var length: Int {
return self.characters.count
}
subscript (
i: Int) -> String {
return self[i ..< i + 1]
}
func substring(
fromIndex: Int) ->
String {
return self[min(fromIndex, length) ..< length]
}
func substring(
toIndex: Int) ->
String {
return self[0 ..< max(0, toIndex)]
}
subscript (
r: Range<Int>) ->
String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start =
index(startIndex, offsetBy: range.lowerBound)
let end =
index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}
// 2й способ
let str = "foo bar baz bax"
// "bar"
print(str[4...6])
// "bar baz bax"
print(str[4...])
// "foo bar"
print(str[...6])
// "foo ba"
print(str[..<6])
extension DefaultBidirectionalIndices {
subscript(at: Int) -> Elements.Index {
return index(startIndex, offsetBy: at)
}
}
extension String {
subscript(r: CountableClosedRange<Int>) ->
SubSequence {
return self[indices[r.lowerBound]...indices[r.upperBound]]
}
subscript(r: CountablePartialRangeFrom<Int>) ->
SubSequence {
return self[indices[r.lowerBound]...]
}
subscript(r: PartialRangeThrough<Int>) ->
SubSequence {
return self[...indices[r.upperBound]]
}
subscript(r: PartialRangeUpTo<Int>) ->
SubSequence {
return self[..<indices[r.upperBound]]
}
}