Skip to content

Commit cbc01be

Browse files
adam-pogdynamitechetan
authored andcommitted
Added caesar cipher algorithm (#13)
1 parent 20bdcfd commit cbc01be

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

ciphers/CaesarCipher.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import (
4+
"bytes"
5+
"flag"
6+
"fmt"
7+
"strings"
8+
)
9+
10+
func main() {
11+
cipherKey := flag.Int("c", 0, "Cipher shift amount (-26 - 26)")
12+
input := flag.String("i", "", "Input")
13+
flag.Parse()
14+
15+
if *cipherKey > 26 || *cipherKey < -26 {
16+
flag.PrintDefaults()
17+
} else {
18+
fmt.Println(caesarCipher(*input, *cipherKey))
19+
}
20+
21+
}
22+
23+
func caesarCipher(input string, key int) string {
24+
var outputBuffer bytes.Buffer
25+
for _, r := range strings.ToLower(input) {
26+
newByte := int(r)
27+
28+
if newByte >= 'a' && newByte <= 'z' {
29+
newByte += key
30+
31+
if newByte > 'z' {
32+
newByte -= 26
33+
} else if newByte < 'a' {
34+
newByte += 26
35+
}
36+
}
37+
38+
outputBuffer.WriteString(string(newByte))
39+
}
40+
return outputBuffer.String()
41+
}

0 commit comments

Comments
 (0)