2019年6月17日 星期一

iOS swift 5: 簡易的的替換式密碼ROT13

 解決方案來源:
  Swift ROT13 Func - Dot Net Perls


func rot13(value: String) -> String 
{ /* https://www.dotnetperls.com/rot13-swift */
    // Empty character array.
    var result = [Character]()
    // Some ASCII constants.
    // A = 65
    // M = 77
    // Z = 90
    // a = 97
    // m = 109
    // z = 122
    let upperA = 65
    let upperM = 77
    let upperZ = 90
    let lowerA = 97
    let lowerM = 109
    let lowerZ = 122

    // Loop over utf8 values in string.
    for u in value.utf8 {

        let s = Int(u)
        var resultCharacter = Character(UnicodeScalar(s))
        if s >= lowerA && s <= lowerZ { // Between a and z.
            if s >= lowerM {
                resultCharacter = Character(UnicodeScalar(s - 13))
            } else {
                resultCharacter = Character(UnicodeScalar(s + 13))
            }
        } else if s >= upperA && s <= upperZ { // Between A and Z.
            if s >= upperM {
                resultCharacter = Character(UnicodeScalar(s - 13))
            } else {
                resultCharacter = Character(UnicodeScalar(s + 13))
            }
        }
        // Append to Character array.
        result.append(resultCharacter)

    }
    // Return String.
    return String(result)
}



沒有留言:

張貼留言