如何在Swift中从字符串中删除变音符号?


75

如何从StringSwift中删除变音符号(或重音符号)(例如说将“één”更改为“ een”)?我必须回到NSStringSwift还是可以在Swift中完成?

Answers:


167

您可以直接在Swift上操作String(如果导入了“ Foundation”):

let foo = "één"
let bar = foo.stringByFoldingWithOptions(.DiacriticInsensitiveSearch, locale: NSLocale.currentLocale())
print(bar) // een

斯威夫特3:

let foo = "één"
let bar = foo.folding(options: .diacriticInsensitive, locale: .current)
print(bar) // een

不错的解决方案!谢谢。
Johan Kool,2015年

一如既往的出色答案。请注意,stringByFoldingWithOptions是NSString中的方法。此利用的NSString和字符串之间的无缝桥接在夫特2.观光夫特3是不同的
邓肯Ç

2
@ codddeer123:类似于stackoverflow.com/a/16837527/1187415中的情况:U-0141带笔划的拉丁大写字母L不会分解为基本字符和组合标记。或者(据我了解),Unicode标准未定义Ł和之间的关系L
Martin R

@MartinR,感谢您的快速回复。所以如果是Ł,我应该手动将其删除?
mikro098

2
@RanLearns:我假设locale: nil将应用通用Unicode规则以及locale: .current当前语言的规则。但是我还没有测试。
马丁R

19

更新到@MartinR的答案… Swift 3扩展提供了用于排序/搜索的字符串,这可能对某人有用……

extension String {
    var forSorting: String {
        let simple = folding(options: [.diacriticInsensitive, .widthInsensitive, .caseInsensitive], locale: nil)
        let nonAlphaNumeric = CharacterSet.alphanumerics.inverted
        return simple.components(separatedBy: nonAlphaNumeric).joined(separator: "")
    }
}

例如

print("Mÿ nâMe ís jÄço´B".forSorting) // "mynameisjacob"

1
现在,您应该认为排序非常依赖于语言环境。例如,在我的语言中,“ ch”是“ h”与“ i”之间的一个字母。对于排序方式,变音符号不敏感,只需使用正确的字符串搜索选项即可。
苏珊(Sulthan)

4
对于排序,您应该使用localizedStandardCompare
rmaddy

1

的答案更新 Swift 5.0.1

func toNoSmartQuotes() -> String {
    let userInput: String = self
    return userInput.folding(options: .diacriticInsensitive, locale: .current)
}

并使用它 someTextField.text.toNoSmartQuotes()


3
请注意,所做的更改大于您的方法名称所隐含的含义。
约翰·库尔

0

这是我的解决方案

迅捷5

    extension String {

        func unaccent() -> String {

            return self.folding(options: .diacriticInsensitive, locale: .current)

        }

    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.