如何根据以下条件转换给定的字符串?
到目前为止我的代码:
// *** Using For loop ***
var text = "I'll BUY THAT for a $1234 dollars!"
var textComponents = text.components(separatedBy: .whitespacesAndNewlines)
for i in 0 ..< textComponents.count {
// -TODO: add code to maintain capitalization & punctuation (i.e.: !, $)
if textComponents[i].count > 3 {
textComponents[i] = "bingo"
}
}
textComponents.joined(separator: " ")
// *** Using Map/Filter ***
var text = "I'll BUY THAT for a $1234 dollars!"
var textComponents = text.components(separatedBy: .whitespacesAndNewlines)
textComponents.map {
// -TODO: add code to maintain capitalization & punctuation (i.e.: !, $)
if $0.count > 3 {
// ERROR: Not able reassign $0
$0 = "bingo"
}
}示例
给出了一个字符串::“我要花1234美元买它!”
预期翻译:“宾果买宾果为$bingo宾果!”
发布于 2019-03-13 02:23:13
您可能至少需要三个替换词,如下所示。它可能不是完整的,因为你的需求现在没有那么固定。
let raw = "I'll BUY THAT for a $1234 dollar!".replacingOccurrences(of: "\\b[A-Z][[a-z0-9]\\']{3,}", with: "Bingo", options: .regularExpression, range: nil)
.replacingOccurrences(of: "\\b[A-Z\\']{4,}", with: "BINGO", options: .regularExpression, range: nil)
.replacingOccurrences(of: "\\b[a-z'\\d]{4,}", with: "bingo", options: .regularExpression, range: nil)
print(raw) // Bingo BUY BINGO for a $bingo bingo!https://stackoverflow.com/questions/55131452
复制相似问题