Skip to content

Instantly share code, notes, and snippets.

@BenDavidAaron
Created March 1, 2023 03:09
Show Gist options
  • Save BenDavidAaron/88cbad58189ff072b243b4c29033d5be to your computer and use it in GitHub Desktop.
Save BenDavidAaron/88cbad58189ff072b243b4c29033d5be to your computer and use it in GitHub Desktop.
Caesar Shift Cipher in Go
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