如何从特定位置

时间:2015-06-12 08:39:17

标签: ios string swift

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

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);

任何帮助?

1 个答案:

答案 0 :(得分:1)

试试这样:

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
    }

}