swift 3获取子字符串的起始索引(作为int) [英] swift 3 get start index (as int) of substring
问题描述
我想获得字符串中子字符串的开始和结束位置。示例:在字符串这是我的名字;如果我提供字符串this,我想知道起始索引是4,结束索引是7。
I would like to get the start and end position of a substring within a string. Example: in the string "hi this is my name"; if I provide the string "this" I would like to know the start index is 4 and end index is 7.
我找到了几个链接,包括这个:
I found several links, including this one:
Swift:获取开始索引字符串中的子字符串
a-substring-in-a-string
Swift: get index of start of a substring in a string a-substring-in-a-string
但它在swift 3中不起作用现在称为范围。
But it doesn´t work in swift 3 as the method is now called range.
我现在正在使用它:
let range = mystring.range(of: "StringSearch")?.lowerBound
返回此
Swift.String.UnicodeScalarView.Index(_position: 15), _countUTF16: 1))
我无法获得整数的位置,因为这是一个指数。
And I cannot obtain the position as an integer as this is an index.
In总结一下,我想在一个int类型的变量中有一个位置,在这种情况下是15。
In summary, I would like to have in a variable of type int the position, in this case 15.
任何人都可以帮助我吗?
Can anyone help me?
谢谢大家。
推荐答案
距离(从:到:)
方法字符串
计算两个<$ c $之间的差额
c> String.Index values:
The distance(from:to:)
method of String
computes the difference
between two String.Index
values:
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
}
实际上它只是将调用转发给字符串的 CharacterView
,所以
上面的结果与
Actually it just forwards the call to the string's CharacterView
, so
the above gives the same result as
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
}
如果您需要所有次出现string:
If you need all occurrences of the string:
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
}
这篇关于swift 3获取子字符串的起始索引(作为int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!