防止重叠替换的一系列String.replaceOccurrences(of :)

时间:2017-11-29 13:51:27

标签: swift string

我想替换字符串中的一些字符,我遇到了这个问题。

这是一个示例字符串:“陈是一个美丽的女人。”

我想用“C”替换字符“ch”,这样我的字符串就会变成“Can is a beautiful ....”但是,当我输入“ch”时,文本会变为“X”。我知道这是因为我的代码中有“kh”和“c”规则,但我需要它们。你有什么建议吗?

let textContent = textView.text
var replace = textContent?.replacingOccurrences(of: "Gi", with: "Z")

replace = replace?.replacingOccurrences(of: "C" , with: "K")
replace = replace?.replacingOccurrences(of: "c" , with: "k")

replace = replace?.replacingOccurrences(of: "KH" , with: "X")
replace = replace?.replacingOccurrences(of: "Kh" , with: "X")
replace = replace?.replacingOccurrences(of: "kh" , with: "x")
replace = replace?.replacingOccurrences(of: "kH" , with: "x")

replace = replace?.replacingOccurrences(of: "Ch" , with: "C")
replace = replace?.replacingOccurrences(of: "CH" , with: "C")
replace = replace?.replacingOccurrences(of: "ch" , with: "c")
replace = replace?.replacingOccurrences(of: "cH" , with: "c")

0 个答案:

没有答案