Search code examples
c#encryptioncaesar-cipher

Problem with cipher crypting uppercase letter c#


having problem with crypting the uppercase letters with basic Cipher cryption code in c#, they just translate to symbols Thanks in advance, I wrote the code below (Ps, labels and textboxes are in swedish but hope i can get help anyway)

The code:

private void btnkryptera_Click(object sender, EventArgs e)
{
    string vanlig = tbxnormaltext.Text;
    int bytanummer = int.Parse(tbxkryptera.Text);

    tbxkryperadtext.Text = görKryptering(vanlig, bytanummer);
}

private static string görKryptering(string ord, int nummer)
{
    char[] längd = ord.ToCharArray();

    for (int i = 0; i < längd.Length; i++)
    {
        //Separate and change letters
        char bokstav = längd[i];

        //Change letters based on which shift
        bokstav = (char)(bokstav + nummer);

        //Delete 26 on 'overflow'
        //Adds 26 on 'overflow'
        if (bokstav > 'z')
        {
            bokstav = (char)(bokstav - 26);
        }
        else if (bokstav < 'a')
        {
            bokstav = (char)(bokstav + 26);
        }

        //Then save
        längd[i] = bokstav;

    }
    return new string(längd);
}

Solution

  • Lowercase letters are numbered from 'a' == 97 to 'z' == 122. Uppercase are 'A' == 65 to 'Z' == 90.

    Thus, your bokstav < 'a' will process your uppercase letters and do so incorrectly.

    Either put specific coding for uppercase, or use ToLower() to convert your plaintext to lowercase.