Search code examples
iosswiftswift4

How to remove zero width spaces from string in Swift?


I need to filter invisible character from a string. In the attached screen shot, string "​Cilantro" has some hidden character and when i get count of this before and after removing hidden character it shows different character count.

I just want to filter invisible characters not special characters, for example I dont want to filter á, ã è etc characters.

Note: I removed hidden characters using "delete" button.

For the reference I am adding here the String with invisible character: "​Cilantro". I am not sure if it will show at your end too.

enter image description here


Solution

  • Swift 5 or later

    You can use new Character isLetter property

    let del = Character(UnicodeScalar(127)!)
    let string = "Cilantro\(del)\(del)"
    print(string.count) // "10\n"
    let filtered = string.filter { $0.isLetter }
    print(filtered.count)  // "8\n"
    

    let string = "cafe\u{301}"
    let filtered = string.filter { $0.isLetter }
    print(filtered)  // "café"
    

    If you just want to remove zero width spaces from your string you can do as follow:


    extension Character {
        static let zeroWidthSpace = Self(.init(0x200B)!)
        var isZeroWidthSpace: Bool { self == .zeroWidthSpace }
    }
    

    extension Bool {
        var negated: Bool { !self }
    }
    

    let str = "​Cilantro"
    print(str.count) // 9
    
    let filtered = str.filter(\.isZeroWidthSpace.negated)
    print(filtered.count) // 8