C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Constants: We use some ASCII constants for letters. There values correspond to uppercase and lowercase letters in ASCII.
ASCII TableUtf8: This accesses and returns the ASCII numeric values from the string's data. We cast these values to Ints.
Convert Int to CharacterIf, else: We test the character values with if and else. We use UnicodeScalar and shift letters 13 places depending on their values.
Return: We return a string based on the values appended to our Character array. We test rot13 in the rest of the program.
Swift program that implements rot13 func
func rot13(value: String) -> String {
// 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)
}
// Test the method.
let input = "Do you have any cat pictures?"
let result = rot13(input)
let roundTrip = rot13(result)
print(input)
print(result)
print(roundTrip)
Output
Do you have any cat pictures?
Qb lbh unir nal png cvpgherf?
Do you have any cat pictures?