首页 > 解决方案 > 如何从字符串中删除特殊字符 \u{e2}

问题描述

我有以下代码func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool

var phoneNumber: String?
if let callIntent = interaction.intent as? INStartVideoCallIntent {
    phoneNumber = callIntent.contacts?.first?.personHandle?.value
} else if let callIntent = interaction.intent as? INStartAudioCallIntent {
     phoneNumber = callIntent.contacts?.first?.personHandle?.value
}

电话号码只有 10 位数字。但是当我检查计数时,它显示 12 位数

在此处输入图像描述

当我打印字符串时

在此处输入图像描述

我努力了

phoneNumber?.trimmingCharacters(in: .whitespacesAndNewlines).count phoneNumber?.trimmingCharacters(in: .symbols).count

但它仍然返回 12

请帮忙

标签: iosswift

解决方案


感谢大家的帮助。你真好

我可以使用找到无效字符

phoneNumber?.map{$0.unicodeScalars.allSatisfy{$0.isASCII}}

它返回

Optional<Array<Bool>>
  ▿ some : 12 elements
    - 0 : false
    - 1 : true
    - 2 : true
    - 3 : true
    - 4 : true
    - 5 : true
    - 6 : true
    - 7 : true
    - 8 : true
    - 9 : true
    - 10 : false
    - 11 : true

我可以用一行来解决这个问题

phoneNumber?.filter{$0.unicodeScalars.allSatisfy{$0.isASCII}}

计数为 10

使用

phoneNumber?.filter{$0.unicodeScalars.allSatisfy{$0.isASCII}}.count

希望对其他人有帮助:)


推荐阅读