是时候承认失败了……
在Objective-C中,我可以使用如下内容:
NSString* str = @"abcdefghi";
[str rangeOfString:@"c"].location; // 2
在Swift中,我看到了类似的东西:
var str = "abcdefghi"
str.rangeOfString("c").startIndex
...但这只是给了我一个字符串。索引,我可以使用它下标回原始字符串,但不能从中提取位置。
FWIW,字符串。Index有一个名为_position的私有ivar,其中有正确的值。我只是不明白怎么会暴露出来。
我知道我自己可以很容易地将其添加到String中。我更好奇在这个新的API中我缺少了什么。
仔细想想,你其实并不需要位置的确切Int版本。范围甚至是字符串。如果需要,Index足以再次获取子字符串:
let myString = "hello"
let rangeOfE = myString.rangeOfString("e")
if let rangeOfE = rangeOfE {
myString.substringWithRange(rangeOfE) // e
myString[rangeOfE] // e
// if you do want to create your own range
// you can keep the index as a String.Index type
let index = rangeOfE.startIndex
myString.substringWithRange(Range<String.Index>(start: index, end: advance(index, 1))) // e
// if you really really need the
// Int version of the index:
let numericIndex = distance(index, advance(index, 1)) // 1 (type Int)
}
// Using Swift 4, the code below works.
// The problem is that String.index is a struct. Use dot notation to grab the integer part of it that you want: ".encodedOffset"
let strx = "0123456789ABCDEF"
let si = strx.index(of: "A")
let i = si?.encodedOffset // i will be an Int. You need "?" because it might be nil, no such character found.
if i != nil { // You MUST deal with the optional, unwrap it only if not nil.
print("i = ",i)
print("i = ",i!) // "!" str1ps off "optional" specification (unwraps i).
// or
let ii = i!
print("ii = ",ii)
}
// Good luck.
斯威夫特5
查找子字符串的索引
let str = "abcdecd"
if let range: Range<String.Index> = str.range(of: "cd") {
let index: Int = str.distance(from: str.startIndex, to: range.lowerBound)
print("index: ", index) //index: 2
}
else {
print("substring not found")
}
查找字符索引
let str = "abcdecd"
if let firstIndex = str.firstIndex(of: "c") {
let index: Int = str.distance(from: str.startIndex, to: firstIndex)
print("index: ", index) //index: 2
}
else {
print("symbol not found")
}