从字符串中删除第n个字符

Uze*_*nte 7 string indexing swift

我已经看到很多方法从字符串中删除最后一个字符.有没有办法根据索引删除任何旧字符?

Air*_*ity 10

虽然字符串索引不是随机访问而不是数字,但您可以按数字前进以访问第n个字符:

var s = "Hello, I must be going"

s.removeAtIndex(advance(s.startIndex, 5))

println(s) // prints "Hello I must be going"
Run Code Online (Sandbox Code Playgroud)

当然,在执行此操作之前,您应该始终检查字符串的长度至少为5!

编辑:正如@MartinR指出的那样,你可以使用提前的with-end-index版本来避免跑过末尾的风险:

let index = advance(s.startIndex, 5, s.endIndex)
if index != s.endIndex { s.removeAtIndex(index) }
Run Code Online (Sandbox Code Playgroud)

与以往一样,期权是您的朋友:

// 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)
}
Run Code Online (Sandbox Code Playgroud)


rma*_*ddy 5

这是一个安全的Swift 4实现。

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")
}
Run Code Online (Sandbox Code Playgroud)