我目前有一个基于新闻标题的字符串,最后有一个-带有我不需要的来源。 示例:“随着华尔街等待美联储关于利率的决定,联邦快递下沉-TheStreet.com”
目前要摆脱它,我正在使用:
if let range = str.range(of: "-"){
str.removeSubrange(range.lowerBound..<str.endIndex)}
但是我遇到了一个问题,如果第一个字符串之后的整个字符串都为2,则将被截断。
例如 “随着华尔街等待美联储的利率决定,联邦快递汇-TheStreet.com股票将走低。”
我的问题是我该怎么做,以便仅将结尾-和之后的字符串删除?
答案 0 :(得分:2)
您可以使用集合的方法lastIndex
来找出破折号的最后一次出现:
var str = "Stock - Lower as Wall Street Awaits Fed's Decision on Rates, FedEx Sinks - TheStreet.com"
if let index = str.lastIndex(where: {$0 == "-"}) {
str.removeSubrange(index...)
}
print(str) // "Stock - Lower as Wall Street Awaits Fed's Decision on Rates, FedEx Sinks "
您还可以使用range(of: String)
设置.backwards
选项:
if let range = str.range(of: " - ", options: .backwards) {
str.removeSubrange(range.lowerBound...)
}
print(str) // "Stock - Lower as Wall Street Awaits Fed's Decision on Rates, FedEx Sinks"
答案 1 :(得分:1)
尝试输入代码:
extension String {
mutating func removeFromLast(_ ch: Character) {
if let index = lastIndex(of: ch) {
removeSubrange(index..<endIndex)
}
}
}
var s = "Stock - Lower as Wall Street Awaits Fed's Decision on Rates, FedEx Sinks - TheStreet.com"
s.removeFromLast("-")
print(s)
// "Stock - Lower as Wall Street Awaits Fed's Decision on Rates, FedEx Sinks "