swiftstring

How to remove duplicate characters from a string in Swift


ruby has the function string.squeeze, but I can't seem to find a swift equivalent.

For example I want to turn bookkeeper -> bokepr

Is my only option to create a set of the characters and then pull the characters from the set back to a string?

Is there a better way to do this?


Solution

  • Edit/update: Swift 4.2 or later

    You can use a set to filter your duplicated characters:

    let str = "bookkeeper"
    var set = Set<Character>()
    let squeezed = str.filter{ set.insert($0).inserted } 
    
    print(squeezed)   //  "bokepr"
    

    Or as an extension on RangeReplaceableCollection which will also extend String and Substrings as well:

    extension RangeReplaceableCollection where Element: Hashable {
        var squeezed: Self {
            var set = Set<Element>()
            return filter{ set.insert($0).inserted }
        }
    }
    

    let str = "bookkeeper"
    print(str.squeezed)      //  "bokepr"
    print(str[...].squeezed) //  "bokepr"