gpt4 book ai didi

swift - 用字符串中的多个值替换多个字符

转载 作者:行者123 更新时间:2023-11-28 05:41:34 24 4
gpt4 key购买 nike

我必须替换字符串中的所有字符。

For i.e var str_Ran = "ahsn45ss74d1a37adgt4t4h1fe"

现在我想替换角色

str_Ran = str_Ran.replaceAll("0", "Y")
str_Ran = str_Ran.replaceAll("5", "p")
str_Ran = str_Ran.replaceAll("8", "B")
str_Ran = str_Ran.replaceAll("7", "m")
str_Ran = str_Ran.replaceAll("4", "c")
str_Ran = str_Ran.replaceAll("1", "g")
str_Ran = str_Ran.replaceAll("3", "F")
str_Ran = str_Ran.replaceAll("6", "U")
str_Ran = str_Ran.replaceAll("2", "t")

我找不到替换字符的正确方法。

最佳答案

创建一个字典,将所有应该像这样替换的字符。然后枚举它并使用replacingOccurrences(of:with:) 方法

var str_Ran: String = "ahsn45ss74d1a37adgt4t4h1fe"
var replacedStr: String {
let dict = ["0": "Y","5": "p","8": "B","7": "m","4": "c","1": "g","3": "F","6": "U","2": "t"]
return dict.reduce(str_Ran) { $0.replacingOccurrences(of: $1.key, with: $1.value) }
}

关于swift - 用字符串中的多个值替换多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573572/

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