Caesar Cipher

Era Scarecrow rtcvb32 at yahoo.com
Sun Feb 11 19:12:45 UTC 2018


On Sunday, 11 February 2018 at 18:01:20 UTC, Mario wrote:
> char[] encrypt(char[] input, char shift)
> {
>     auto result = input.dup;
>     result[] += shift;
>     return result;
> }
>
>
> What's wrong? I mean, I know that z is being converted into a 
> symbol, but how should I fix this?

  If you take Z (25) and add 10, you get 35. You need to have it 
identify and fix the problem, namely removing 26 from the result.

  Assuming anything can be part of the input (and not just 
letters), we instead do the following:

     auto result = input.dup;
     foreach(ref ch; result) {
         if (ch >= 'A' && ch <= 'Z')
             ch = ((ch+shift-'A') % 26) + 'A';
     }

  Alternatively if you do where every character is defined for 
switching (and those not changing are the same) it could just be 
a replacement & lookup.



More information about the Digitalmars-d-learn mailing list