Created
March 1, 2023 03:09
-
-
Save BenDavidAaron/88cbad58189ff072b243b4c29033d5be to your computer and use it in GitHub Desktop.
Caesar Shift Cipher in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"flag" | |
"fmt" | |
"os" | |
) | |
var shift = flag.Int("n", 1, "Number of characters to shift") | |
func shiftChar(char rune, shift int) rune { | |
s := int(char) + shift | |
if s > 'z' { | |
return rune(s - 26) | |
} else if s < 'a' { | |
return rune(s + 26) | |
} | |
return rune(s) | |
} | |
func shiftText(text string, shift int) string { | |
runes := []rune(text) | |
shiftedRunes := []rune{} | |
for _, r := range runes{ | |
shiftedRunes = append(shiftedRunes, shiftChar(r, shift)) | |
} | |
shiftedString := string(shiftedRunes) | |
return shiftedString[:len(runes) - 1] | |
} | |
func main() { | |
flag.Parse() | |
reader := bufio.NewReader(os.Stdin) | |
text, _ := reader.ReadString('\n') | |
shiftedText := shiftText(text, *shift) | |
fmt.Println(shiftedText) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment