Caesar cipher: Difference between revisions

Content added Content deleted
(Updated D code)
Line 176: Line 176:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, std.traits, std.ctype, std.conv;
<lang d>import std.stdio, std.ascii;


S rot(S)(S s, int key) if (isSomeString!S) {
string rot(immutable string txt, in int key) pure nothrow {
dchar[] r = new dchar[s.length];
char[] r;

foreach (i, dchar c; s) {
foreach (c; txt)
if (islower(c))
if (isLower(c))
c = ((c - 'a' + key) % 26 + 'a');
r ~= (c - 'a' + key) % 26 + 'a';
else if (isupper(c))
else if (isUpper(c))
c = ((c - 'A' + key) % 26 + 'A');
r ~= (c - 'A' + key) % 26 + 'A';
r[i] = c;
else
}
r ~= c;

return to!S(r);
return r;
}
}


Line 203: Line 204:
Decrypted: The five boxing wizards jump quickly</pre>
Decrypted: The five boxing wizards jump quickly</pre>
Simpler in-place version (same output):
Simpler in-place version (same output):
<lang d>import std.stdio, std.ctype;
<lang d>import std.stdio, std.ascii;


void inplaceRot(char[] txt, in int key) {
void inplaceRot(char[] txt, in int key) pure nothrow {
foreach (ref c; txt) {
foreach (ref c; txt) {
if (islower(c))
if (isLower(c))
c = cast(char)((c - 'a' + key) % 26 + 'a');
c = (c - 'a' + key) % 26 + 'a';
else if (isupper(c))
else if (isUpper(c))
c = cast(char)((c - 'A' + key) % 26 + 'A');
c = (c - 'A' + key) % 26 + 'A';
}
}
}
}