我正在寻找一种快速替换字符串中的单词的方法。有人可以帮忙吗?
这是我到目前为止所能找到的特定单词,但是我不知道如何替换它。
var str = "helo, playgound"
var findWords = ["helo","playgound"]
var replaceWords = ["hello","playground"]
extension String {
var wordList:[String] {
return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())).componentsSeparatedByString(" ")
}
}
func stringToArray() -> Array<String> {
var arr = str.wordList
return arr
}
func correction(var _arr:Array<String>) -> String{
for var i = 0; i < _arr.count; i++ {
if str.lowercaseString.rangeOfString(findWords[i]) != nil {
println("exists")
}
}
return str
}
这取决于您对“单词”的定义。如果您正在寻找“字”的智能内置概念,则最简单的解决方案可能是使用NSRegularExpression,它知道“字”边界在哪里:
var s = NSMutableString(string:"hello world, go to hell")
let r = NSRegularExpression(
pattern: "\\bhell\\b",
options: .CaseInsensitive, error: nil)!
r.replaceMatchesInString(
s, options: nil, range: NSMakeRange(0,s.length),
withTemplate: "heaven")
之后,s
是"hello world, go to heaven"
,这是正确的答案;我们用单词“ hell”代替了“ hello”中的“ hell”。请注意,我们也区分大小写,这似乎是您的愿望清单之一。
该示例说明了如何只进行一对(“ hell”和“ heaven”)的操作,但是很容易将其抽象为一种方法,以便您可以为另一对进行一次又一次的操作:
var str = "helo, playgound"
var findWords = ["helo", "playgound"]
var replaceWords = ["hello", "playground"]
func correct(str:String, orig:String, repl:String) -> String {
var s = NSMutableString(string:str)
let r = NSRegularExpression(
pattern: "\\b\(orig)\\b",
options: .CaseInsensitive, error: nil)!
r.replaceMatchesInString(
s, options: nil, range: NSMakeRange(0,s.length),
withTemplate: repl)
return s
}
for pair in Zip2(findWords,replaceWords) {
str = correct(str, pair.0, pair.1)
}
str // hello, playground
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句