Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove nth character from string

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?

like image 481
Uzebeckatrente Avatar asked Jan 29 '15 15:01

Uzebeckatrente


2 Answers

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")
}
like image 110
rmaddy Avatar answered Nov 13 '22 04:11

rmaddy


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)
}
like image 43
Airspeed Velocity Avatar answered Nov 13 '22 05:11

Airspeed Velocity