Search code examples
stringswift3characteralphabetical

How to replace each letter in a string with the letter following it in the alphabet?


I have to solve this situation, and I have been looking for a solution with no success. I tried to do this by getting the unicode scalars for each character in the string, but I am not able to make this work.

Could somebody help me to implement this transformation? I'm developing in Swift 3.


Solution

  • String has a property called unicodeScalars that you can get its value. Just increment each value from your string using UnicodeScalar initializer and flatMap, and use reduce to combine them into the final string:

    extension String {
        var shiftedCharacters: String {
            return unicodeScalars.lazy
                .flatMap{UnicodeScalar($0.value+1)}
                .reduce("", {$0 + String($1)})
        }
    }
    

    Another option is to create a String UnicodeScalarView with the unicodeScalars and initialize a new string from it:

    extension String {
        var shiftedCharacters: String {
            return String(String.UnicodeScalarView(
                unicodeScalars.lazy
                .flatMap{ UnicodeScalar($0.value+1) }
            ))
        }
    }
    

    Testing:

    "abcde".shiftedCharacters // "bcdef"
    "car".shiftedCharacters   // "dbs"