Remove nth character from string

前端 未结 4 1504
无人及你
无人及你 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:46

    Swift 3.2

    let str = "hello"
    let position = 2
    let subStr = str.prefix(upTo: str.index(str.startIndex, offsetBy: position)) + str.suffix(from: str.index(str.startIndex, offsetBy: (position + 1)))
    print(subStr)
    

    "helo"

    0 讨论(0)
  • 2021-01-05 01:48

    var hello = "hello world!"

    Let's say we want to remove the "w". (It's at the 6th index position.)

    First: Create an Index for that position. (I'm making the return type Index explicit; it's not required).

    let index:Index = hello.startIndex.advancedBy(6)

    Second: Call removeAtIndex() and pass it our just-made index. (Notice it returns the character in question)

    let choppedChar:Character = hello.removeAtIndex(index)

    print(hello) // prints hello orld!

    print(choppedChar) // prints w

    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2021-01-05 01:54

    Here is a safe Swift 4 implementation.

    var s = "Hello, I must be going"
    var n = 5
    if let index = s.index(s.startIndex, offsetBy: n, limitedBy: s.endIndex) {
        s.remove(at: index)
        print(s) // prints "Hello I must be going"
    } else {
        print("\(n) is out of range")
    }
    
    0 讨论(0)
提交回复
热议问题