在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))
- print(underFive.contains(6.28))
- print(underFive.contains(5.0))
-
- 注意:Range实例能够代表一个空的范围,如下:
-
- let empty =0.0..<0.0
- print(empty.contains(0.0))
- print(empty.isEmpty)
具体使用
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:从字符串指定范围查找特定字符串
-
- let startIndex: String.Index =str.startIndex
- str[startIndex]
-
-
- let endIndex: String.Index =str.endIndex
-
-
-
- let afterIndex: String.Index =str.index(after:startIndex)
- str[afterIndex]
-
-
- let afterRange = str.index(after:startIndex)..<str.endIndex
- str[afterRange]
-
-
- let beforeIndex: String.Index =str.index(before:str.endIndex)
- str[beforeIndex]
-
-
-
-
- let offsetIndex: String.Index =str.index(str.startIndex, offsetBy:12)
- str[offsetIndex]
-
- let offsetRange = startIndex ..< offsetIndex
- str[offsetRange]
-
-
- if let index =str.index(str.startIndex, offsetBy:10, limitedBy: str.endIndex){
- str[index]
- }
-
- let subStringRange = str.range(of:"Merry", options: .caseInsensitive, range:offsetRange)
- print(subStringRange)
-
-
- 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)")
- }
- else {
- print("Not found")
- }
3:截取子串
- let subIndex: String.Index =str.index(str.startIndex, offsetBy:12)
-
- str.substring(to:endIndex)
- str.substring(from:subIndex)
- str.substring(with:subIndex..<endIndex)
- str
4:插入字符到字符串
- str.insert("L", at:startIndex)
5:末尾追加字符串
- str.append("A Apple day!")
6:使用字符串替换指定范围的子字符串
- str.replaceSubrange(str.startIndex..<str.index(str.startIndex, offsetBy: 6), with:"Hello")
7:去除字符
- str.remove(at:startIndex)
- str.removeSubrange(subIndex..<endIndex)
- str.removeAll()
- str
|