在Swift字符串的检索中,有时候返回的可能是一个范围,而不是一个具体的位置.下面看一下String.Index和 Range
String.Index:表示在字符的CharacterView实例的位置,进入头文件就可以看到,其实是public typealias Index = String.CharacterView.Index。
Range:一个半开半闭的可比较范围,从下界(lower bound)到上界(upper bound),但是不包括上界。我们可以使用半开半闭操作符(..<)来创建Range实例。而且我们可以使用该实例来迅速确认一个值是否在该范围之内,如:
let underFive =0.0..<5.0
print(underFive.contains(3.14)) // Prints "true"
print(underFive.contains(6.28)) // Prints "false"
print(underFive.contains(5.0)) // Prints "false"
注意:Range实例能够代表一个空的范围,如下:
let empty =0.0..<0.0
print(empty.contains(0.0)) // Prints "false"
print(empty.isEmpty) // Prints "true"
具体使用
var str = "Hello Merry Christmas day!"
1:搜索字符串
let range = str.range(of:"Hello") //正向检索
let backWardsRange = str.range(of:"Hello", options: .backwards)//反向检索
let caseInsensitiveRange = str.range(of:"day", options: .caseInsensitive, range:nil , locale:nil)//忽略大小写
2:从字符串指定范围查找特定字符串
//startIndex 第一个字符的位置
let startIndex: String.Index =str.startIndex
str[startIndex]//H
//endIndex 最后一个字符的位置
let endIndex: String.Index =str.endIndex
//str[endIndex] // error: after last character,fatal error: Can't form a Character from an empty String
//after 给定位置之后的字符位置
let afterIndex: String.Index =str.index(after:startIndex)
str[afterIndex]//e
//range 指定范围
let afterRange = str.index(after:startIndex)..<str.endIndex
str[afterRange]//ello Merry Christmas day!
//before 给定位置之前的字符位置
let beforeIndex: String.Index =str.index(before:str.endIndex)
str[beforeIndex]//!
//offsetBy 偏移量,可以是正数或者负数
//这里是以字符串开始位置为标准,向后偏移21个位置
let offsetIndex: String.Index =str.index(str.startIndex, offsetBy:12)
str[offsetIndex]//C
let offsetRange = startIndex ..< offsetIndex
str[offsetRange]//Hello Merry
//limitedBy 给定限制范围,确保不会越界
if let index =str.index(str.startIndex, offsetBy:10, limitedBy: str.endIndex){
str[index]//y
}
let subStringRange = str.range(of:"Merry", options: .caseInsensitive, range:offsetRange)
print(subStringRange)
//distance 查找字符的位置
let string = "Hello.World"
let needle: Character ="."
if let idx =string.characters.index(of:needle) {
let pos =string.characters.distance(from:string.startIndex, to: idx)
print("Found\(needle) at position\(pos)")//Found . at position 5
}
else {
print("Not found")
}
3:截取子串
let subIndex: String.Index =str.index(str.startIndex, offsetBy:12)
str.substring(to:endIndex) //从开始位置到endIndex范围内的字符
str.substring(from:subIndex) //从subIndex到最后范围内的字符
str.substring(with:subIndex..<endIndex)//截取某一个范围内的字符
str //注意:对字符串进行截取操作,原来的字符串不变 Hello Merry Christmas day!
4:插入字符到字符串
str.insert("L", at:startIndex)//LHello Merry Christmas day!
5:末尾追加字符串
str.append("A Apple day!")//LHello Merry Christmas day!A Apple day!
6:使用字符串替换指定范围的子字符串
str.replaceSubrange(str.startIndex..<str.index(str.startIndex, offsetBy: 6), with:"Hello") //"Hello Merry Christmas day!A Apple day!
7:去除字符
str.remove(at:startIndex) //去除指定位置的字符
str.removeSubrange(subIndex..<endIndex)//去除指定范围的字符
str.removeAll()//去除所有 str