Swift: 如何替换数组中的大写符号

Swift: How to replace uppercase symbols in array

这是将西里尔字母替换为拉丁字母的代码:

let cyr = ["а", "б", "в", "г", "д", "Б"]
let latin = ["a", "b", "v", "g", "d", "B"]
var original = self.input.text        
for i in 0..<cyr.count {
    let target = cyr[i]
    let destination = latin[i]  
    original = original?.replacingOccurrences(of: target, with: destination, options: String.CompareOptions(rawValue: NSString.CompareOptions.caseInsensitive.rawValue | NSString.CompareOptions.literal.rawValue), range: nil)
    self.output.text = original;

但是如果我将它们添加到数组中,它不会将大写符号替换为大写符号。它要么将所有小写字母替换为大写字母,要么将所有小写字母替换为大写字母。如何区分大写和小写分别替换?

删除 caseInsensitive 选项并将大写字母添加到数组中。

let cyr = ["а", "б", "в", "г", "д", "Б", "А", ...]
let latin = ["a", "b", "v", "g", "d", "B", "A", ...]
var original = self.input.text        
for i in 0..<cyr.count {
    let target = cyr[i]
    let destination = latin[i]  
    original = original?.replacingOccurrences(of: target, with: destination, options: [.literal], range: nil)
}
self.output.text = original

当您需要大小写 敏感 搜索和替换时,不应使用 caseInsensitive 选项。您的代码也可以简化为

let cyr = ["а", "б", "в", "г", "д", "Б"]
let latin = ["a", "b", "v", "g", "d", "B"]

var text = "абвгдБ"

for (src, dest) in zip(cyr, latin) {
    text = text.replacingOccurrences(of: src, with: dest)
}
print(text) // abvgdB

话虽如此,您真正想要的可能是 音译 到拉丁语:

let original = "абвгдБ"
let trans = original.applyingTransform(.toLatin, reverse: false) ?? original
print(trans) // abvgdB