RosettaCodeData/Task/Caesar-cipher/D/caesar-cipher-1.d

23 lines
585 B
D
Raw Permalink Normal View History

2013-04-10 16:57:12 -07:00
import std.stdio, std.traits;
2015-02-20 00:35:01 -05:00
S rot(S)(in S s, in int key) pure nothrow @safe
2013-06-05 21:47:54 +00:00
if (isSomeString!S) {
2015-02-20 00:35:01 -05:00
auto res = s.dup;
2013-04-10 16:57:12 -07:00
2013-06-05 21:47:54 +00:00
foreach (immutable i, ref c; res) {
2013-04-10 16:57:12 -07:00
if ('a' <= c && c <= 'z')
c = ((c - 'a' + key) % 26 + 'a');
else if ('A' <= c && c <= 'Z')
c = ((c - 'A' + key) % 26 + 'A');
}
2013-06-05 21:47:54 +00:00
return res;
2013-04-10 16:57:12 -07:00
}
2015-02-20 00:35:01 -05:00
void main() @safe {
2013-06-05 21:47:54 +00:00
enum key = 3;
immutable txt = "The five boxing wizards jump quickly";
2013-04-10 16:57:12 -07:00
writeln("Original: ", txt);
writeln("Encrypted: ", txt.rot(key));
writeln("Decrypted: ", txt.rot(key).rot(26 - key));
}