Swift:条件字符串转换

标签 swift string

如何根据以下标准翻译给定的字符串?

  • 所有超过 3 个字符的单词都应翻译为该单词 “宾果游戏”
  • 必须保持大写
  • 单词中的标点符号(例如 we'll)可以被丢弃,所有其他标点符号必须保留。

到目前为止我的代码:

// *** 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 BUY BINGO for $bingo bingo!”

最佳答案

您可能需要至少三个替换词,如下所示。它可能不完整,因为您的要求现在还没有那么固定。

  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!

关于Swift:条件字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55131452/

相关文章:

string - 在编写值向量和换行符时避免多次调用 fprintf

python - 加速 Python 中输出重复产品的函数

arrays - 过滤数组但保持 indexPath 位置

ios - 如何将 UITableView 与具有 UISwitch 的单元格一起使用并为全选添加一个开关?

ios - 无法生成具有旧节数 : 1 and new section count: 0 with FetchedResultsController 的新节图

ios - 制作一个应用程序,我想让照片可选,但在制作新帖子时需要标题

swift - Xcode 10 没有构建最新的 swift 文件

Java不可靠的字符串RSA加密/解密

javascript - 为什么我会收到 ParseError?

java - 如何在 JSTL/JSP 的循环中连接字符串?