rog*_*rog 17 indexing substring swift swift3
我想获得字符串中子字符串的开始和结束位置.示例:在字符串"嗨,这是我的名字"; 如果我提供字符串"this",我想知道起始索引是4,结束索引是7.
我发现了几个链接,包括这个链接:
Swift:获取字符串 a-substring-in-a-string中子字符串的起始索引
但它在swift 3中不起作用,因为该方法现在称为范围.
我现在用这个:
let range = mystring.range(of: "StringSearch")?.lowerBound
Run Code Online (Sandbox Code Playgroud)
返回此
Swift.String.UnicodeScalarView.Index(_position: 15), _countUTF16: 1))
Run Code Online (Sandbox Code Playgroud)
我无法获得整数的位置,因为这是一个索引.
总之,我想在一个int类型的变量中使用位置,在本例中为15.
谁能帮我?
感谢大家.
Mar*_*n R 25
计算两个值之间差异的distance(from:to:)方法:StringString.Index
let mystring = "hi this is my name"
if let range = mystring.range(of: "this") {
let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound)
let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound)
print(startPos, endPos) // 3 7
}
Run Code Online (Sandbox Code Playgroud)
实际上它只是将调用转发给字符串CharacterView,所以上面给出了相同的结果
let mystring = "hi this is my name"
if let range = mystring.range(of: "this") {
let startPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.lowerBound)
let endPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.upperBound)
print(startPos, endPos) // 3 7
}
Run Code Online (Sandbox Code Playgroud)
如果您需要所有出现的字符串:
let mystring = "this is this and that is that"
var searchPosition = mystring.startIndex
while let range = mystring.range(of: "this", range: searchPosition..<mystring.endIndex) {
let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound)
let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound)
print(startPos, endPos)
searchPosition = range.upperBound
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11084 次 |
| 最近记录: |