gpt4 book ai didi

Swift:条件字符串转换

转载 作者:行者123 更新时间:2023-11-30 10:48:44 25 4
gpt4 key购买 nike

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

  • 所有超过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com