1

What is the best Data Structure(DS)/Class I can use to implement Caesar's Cipher ? This is what I have thought of so far:

  1. String with all alphabets (abc...zABCD...Z) ?
  2. Array with alphabets and wraparound ?
  3. DS which stores a key value pair ?

Why i thought i need 3 - I have to find the character (which is to be encoded) in my "list of numbered alphabets". Then i use that index, and shift it by a number. I thought that it would be faster if i used key value pair instead of searching each index of string or array.

FirstName LastName
  • 639
  • 2
  • 8
  • 21

1 Answers1

1
public String applyCaesar(String text, int shift)
{
    char[] chars = text.toCharArray();
    for (int i=0; i < text.length(); i++)
    {
        char c = chars[i];
        if (c >= 32 && c <= 127)
        {
            // Change base to make life easier, and use an
            // int explicitly to avoid worrying... cast later
            int x = c - 32;
            x = (x + shift) % 96;
            if (x < 0) 
              x += 96; //java modulo can lead to negative values!
            chars[i] = (char) (x + 32);
        }
    }
    return new String(chars);
}
TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57