gpt4 book ai didi

swift - 检查数字的语言是英语还是阿拉伯语/波斯语

转载 作者:行者123 更新时间:2023-11-28 08:05:40 27 4
gpt4 key购买 nike

在我的项目中,我计划将任何类型编号的语言更改为波斯语,这是我所做的:

public extension String {
func perstianString (string: String)->String {
let digitSet = CharacterSet.decimalDigits
var finalString = String()
for ch in string.unicodeScalars {
if digitSet.contains(ch) {
let sh = convertoPersianNum(num: "\(ch)")
finalString += sh
}
} else {
finalString += "\(ch)"
}
}
return finalString
}

func convertoPersianNum(num: String)->String{
var retVlue = String()
var num1 = num

let number = NSNumber(value: Int(num1)!)

let numb = (num as NSString).intValue
let format = NumberFormatter()
format.locale = Locale(identifier: "fa_IR")
let faNumber = format.string(from: number)

return faNumber!
}
}

但是当源值包含波斯数字时,应用程序会崩溃。简单地说,我想检查它是否是波斯数字,什么都不做,否则进行上面的转换:

let string = "ییسس ۱۲۳۴"

对于这种类型,不要做任何其他事情。

最佳答案

public extension String {

private var isPersian: Bool {

let predicate = NSPredicate(format: "SELF MATCHES %@", "(?s).*\\p{Arabic}.*")
return predicate.evaluate(with: self)
}

private var toPersianNum: String {

let number = NSDecimalNumber(string: self)
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "fa_IR")
return formatter.string(from: number) ?? ""
}

var persian:String {

var retVal = String()

self.enumerateSubstrings(in: startIndex..<endIndex, options: .byComposedCharacterSequences) { (string, _, _, _) in
guard let string = string else {return}

if string.isPersian {
retVal += string
}else {
retVal += string.toPersianNum
}
}
return retVal
}
}


let string = "9001ییسس2345777 ۱۲۳۴2345"

string.persian // "۹۰۰۱ییسس۲۳۴۵۷۷۷ناعدد۱۲۳۴۲۳۴۵" (result)

关于swift - 检查数字的语言是英语还是阿拉伯语/波斯语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220464/

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