swift中的子串会感觉非常复杂
我想要
abc
来自
word(abc)
最简单的方法是什么?
如何修复以下代码?
let str = "word(abc)"
// get index of (
let start = str.rangeOfString("(")
// get index of )
let end = str.rangeOfString(")")
// substring between ( and )
let substring = str[advance(str.startIndex, start!.startIndex), advance(str.startIndex, end!.startIndex)]
答案 0 :(得分:9)
Xcode 8.2•Swift 3.0.2
let text = "word(abc)"
// substring between ( and )
if let start = text.range(of: "("),
let end = text.range(of: ")", range: start.upperBound..<text.endIndex) {
let substring = text[start.upperBound..<end.lowerBound] // "abc"
} else {
print("invalid input")
}
答案 1 :(得分:0)
您可以使用stringByReplacingOccurrencesOfString
:
var a = "word(abc)" // "word(abc)"
a = a.stringByReplacingOccurrencesOfString("word(", withString: "") // "abc)"
a = a.stringByReplacingOccurrencesOfString(")", withString: "") // "abc"
或循环解决方案:
var a = "word(abc)"
for component in ["word(", ")"] {
a = a.stringByReplacingOccurrencesOfString(component, withString: "")
}
对于更复杂的东西,正则表达式会更整洁。
答案 2 :(得分:0)
使用正则表达式。
let str = "ds)) ) ) (kj( (djsldksld (abc)"
var range: Range = str.rangeOfString("\\([a-zA-Z]*\\)", options:.RegularExpressionSearch)!
let subStr = str.substringWithRange(range).stringByReplacingOccurrencesOfString("\\(", withString: "", options: .RegularExpressionSearch).stringByReplacingOccurrencesOfString("\\)", withString: "", options: .RegularExpressionSearch)
println("subStr = \(subStr)")