在Swift中String
对象中删除特定字符后所有字符的更优雅方法是什么?
假设我有以下字符串:
str.str
我需要删除" .str"从中。我该怎么办?
提前致谢。
答案 0 :(得分:35)
这是一种方法:
var str = "str.str"
if let dotRange = str.rangeOfString(".") {
str.removeRange(dotRange.startIndex..<str.endIndex)
}
<强>更新强> 在Swift 3中它是:
var str = "str.str"
if let dotRange = str.range(of: ".") {
str.removeSubrange(dotRange.lowerBound..<str.endIndex)
}
答案 1 :(得分:20)
我认为这是更好的方法:
使用 Swift 4 进行更新: (现在不推荐使用子字符串)
let smth = "element=value"
if let index = (smth.range(of: "=")?.upperBound)
{
//prints "value"
let afterEqualsTo = String(smth.suffix(from: index))
//prints "element="
let beforeEqualsToContainingSymbol = String(smth.prefix(upTo: index))
}
if let index = (smth.range(of: "=")?.lowerBound)
{
//prints "=value"
let afterEqualsToContainingSymbol = String(smth.suffix(from: index))
//prints "element"
let beforeEqualsTo = String(smth.prefix(upTo: index))
}
答案 2 :(得分:15)
相当紧凑的方式是:
var str = "str.str"
str = str.componentsSeparatedByString(".")[0]
您可能感兴趣的另一个选项,适用于您的示例'str.str',但不符合您的规范:
str = str.stringByDeletingPathExtension
// Returns a new string made by deleting the extension (if any, and only the last)
// from the `String`
答案 3 :(得分:2)
这适用于 swift 5,字面上需要一行
textString = textString.components(separatedBy: ".")[0]
答案 4 :(得分:0)
/**
* Splits a string at the first occurrence of a delimiter string
* ## Examples:
* splitAtFirst(str: "element=value", delimiter: "=") // "element", "value"
*/
public static func splitAtFirst(str: String, delimiter: String) -> (a: String, b: String)? {
guard let upperIndex = (str.range(of: delimiter)?.upperBound), let lowerIndex = (str.range(of: delimiter)?.lowerBound) else { return nil }
let firstPart: String = .init(str.prefix(upTo: lowerIndex))
let lastPart: String = .init(str.suffix(from: upperIndex))
return (firstPart, lastPart)
}