how to find the index of a character in a string from specific position

后端 未结 1 950
谎友^
谎友^ 2021-01-23 17:24

I know how to find an index of a character like the following:

func indexOfCharacter(myString:String, char: Character) -> Int {
        if let idx = find(mySt         


        
相关标签:
1条回答
  • 2021-01-23 18:25

    Try like this:

    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
    

    update: 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
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题