Swift:条件字符串转换

时间:2019-03-12 22:16:01

标签: swift string

如何根据以下条件翻译给定的字符串?

  • 所有大于3个字符的单词都应翻译为该单词 “宾果”
  • 必须保持大写字母
  • 单词中的标点符号(例如我们将被丢弃),必须保留所有其他标点符号。

到目前为止我的代码:

// *** 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美元的价格购买该商品!”

预期的翻译版本::“宾果公司为宾果游戏宾果游戏购买宾果!”

0 个答案:

没有答案