3

Im doing a caesar cipher and decipher, and i need to ignore this letters from the String: "á é ó í ú", cause we need to cipher text in spanish too, is there any function to ignore this letters or a way to change them in the cipher and still work in the decipher?

private char cipher(char ch, int key)
        {
            if (!char.IsLetter(ch))
            {
                return ch;
            }
            char d = char.IsUpper(ch) ? 'A' : 'a';
            return (char)((((ch + key) - d) % 26) + d);
        }

something i expect is, if i enter a String like : "wéts" with a key an2, i get an output "uéiy" and when i decipher the "uéiy" i get "wéts" again

Esteban
  • 55
  • 6
  • This looks like modulo math on a 26 character (Latin?) alphabet - which is clearly not going to work when you accept more than the 26 characters. Teach your system about the other characters. – Sam Axe Oct 18 '19 at 18:40

1 Answers1

1

Sure, here you go, here's 65536 character alphabet caesar cipher implementation:

private char cipher(char ch, int key)
{
  return ch + key;
}
private char decipher(char ch, int key)
{
  return ch - key;
}

or here's one that just ignore non-latin letters:

private char cipher(char ch, int key)
{
  if (char < 'A' || char > 'z' || (char > 'Z' && char < 'a'))
  {
    return ch;
  }
  char d = char.IsUpper(ch) ? 'A' : 'a';
  return (char)((((ch + key) - d) % 26) + d);
}
Robert McKee
  • 21,305
  • 1
  • 43
  • 57