gpt4 book ai didi

ios - 如何从特定位置查找字符串中字符的索引

转载 作者:行者123 更新时间:2023-11-28 07:05:21 25 4
gpt4 key购买 nike

我知道如何找到如下字符的索引:

func indexOfCharacter(myString:String, char: Character) -> Int {
if let idx = find(myString, char) {
return distance(self.startIndex, idx)
}else{
return -1;
}

}

如何查找特定位置后的索引?

例子:myString="abcdabcd"

我想得到第二个 'd' = 7 的索引

indexOfCharacter(myString,character : 'd',fromIndex: 4);

有什么帮助吗?

最佳答案

像这样尝试:

func indexOfCharacter(myString:String, char: Character,fromIndex: Int) -> Int {

let sub = myString.substringFromIndex(advance(myString.startIndex, fromIndex))
if let idx = find(sub, char) {
return distance(sub.startIndex, idx) + fromIndex
}else{
return -1
}

}

let myString = "abcdabcd"

indexOfCharacter(myString, "d", 4) // 7

更新:Xcode 7.3 • Swift 2.2

func indexOfCharacter(myString:String, char: Character, fromIndex: Int) -> Int {

let sub = myString.substringFromIndex(myString.startIndex.advancedBy(fromIndex))
if let idx = sub.characters.indexOf(char){
return sub.startIndex.distanceTo(idx) + fromIndex
}else{
return -1
}

}

关于ios - 如何从特定位置查找字符串中字符的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com