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

时间:2015-01-29 15:32:54

标签: string swift indexing

我见过许多从字符串中删除最后一个字符的方法。有没有办法根据索引删除任何旧字符?

4 个答案:

答案 0 :(得分:10)

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

var s = "Hello, I must be going"

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

println(s) // prints "Hello I must be going"

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

编辑:正如@MartinR指出的那样,你可以使用提前的with-end-index版本来避免超越结束的风险:

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

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

// 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)
}

答案 1 :(得分:3)

这是一个安全的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")
}

答案 2 :(得分:1)

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”

答案 3 :(得分:0)

var hello = "hello world!"

我们想要删除" w"。 (它位于第6个指数位置。)

首先:为该位置创建一个索引。 (我将返回类型索引显式化;不需要它。)

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

第二:调用 removeAtIndex()并将其传递给我们刚刚制作的索引。 (注意它返回有问题的字符)

let choppedChar:Character = hello.removeAtIndex(index)

print(hello) //打印 hello orld!

print(choppedChar) //打印 w