Remove nth character from string

前端 未结 4 1503
无人及你
无人及你 2021-01-05 01:30

I have seen many methods for removing the last character from a string. Is there however a way to remove any old character based on its index?

4条回答
  •  囚心锁ツ
    2021-01-05 01:54

    While string indices aren't random-access and aren't numbers, you can advance them by a number in order to access the nth character:

    var s = "Hello, I must be going"
    
    s.removeAtIndex(advance(s.startIndex, 5))
    
    println(s) // prints "Hello I must be going"
    

    Of course, you should always check the string is at least 5 in length before doing this!

    edit: as @MartinR points out, you can use the with-end-index version of advance to avoid the risk of running past the end:

    let index = advance(s.startIndex, 5, s.endIndex)
    if index != s.endIndex { s.removeAtIndex(index) }
    

    As ever, optionals are your friend:

    // find returns index of first match,
    // as an optional with nil for no match
    if let idx = s.characters.index(of:",") {
        // this will only be executed if non-nil,
        // idx will be the unwrapped result of find
        s.removeAtIndex(idx)
    }
    

提交回复
热议问题