我看过很多删除字符串最后一个字符的方法。但是是否有一种方法可以根据其索引删除任何旧字符呢?
这里是一个安全的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")
}
var s = "Hello, I must be going"
s.removeAtIndex(advance(s.startIndex, 5))
println(s) // prints "Hello I must be going"
当然,在这之前,你应该始终检查字符串长度至少为5个字符!
编辑:如@MartinR所指出的那样,你可以使用advance的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)
}
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)
"你好"
var hello = "hello world!"
假设我们想要删除 "w"。(它在第6个索引位置。)
第一步:为该位置创建一个索引。(我明确地指定了返回类型Index;这不是必需的。)
let index:Index = hello.startIndex.advancedBy(6)
第二步:调用removeAtIndex()并传递刚刚制作的索引。(注意它返回所需的字符)
let choppedChar:Character = hello.removeAtIndex(index)
print(hello)
// 输出 hello orld!
print(choppedChar)
// 输出 w
let index = advance(s.startIndex, 5, s.endIndex); if index != s.endIndex { s.removeAtIndex(index) }
。 - Martin Rfind
,这将是一件好事,但我想这意味着在你想包括实际索引为end
而不是索引结束标记的情况下,它会变得不那么有用。 - Airspeed Velocityadvance()
方法返回有效(非可选)索引的事实。 - Martin Rfunc advance<T : ForwardIndexType>(start: T, n: T.Distance, end: T) -> T? { let idx = Swift.advance(start, n, end); return idx == end ? nil : idx }
。然后您可以在没有问题的情况下使用它与if let
,但对于非可选版本,必须执行let idx = advance(s.startIndex, 5, s.endIndex) as String.Index
。 - Airspeed Velocity