Search code examples
c#caesar-cipher

Issue with removing spaces from string in caesar cipher c#


I'm trying to make a Caesar cipher program, however I am unable to remove the spaces from the final encrypted output. I used:

if (letter == ' ')
                continue;

However this seems to not be working and I can't identify what is causing the issue. I haven't been working with C# very long so it may potentially be a stupid error.

If I was to input the phrase with a shift of 7: "I need help" the following output would be pAullkAolsw with all spaces becoming uppercase A. The output I wish to have should be in the example: p ullk olsw.

Below is my full code:

using System;

class Program
{

static string Caesar(string value, int shift)
{
    char[] buffer = value.ToCharArray();
    for (int i = 0; i < buffer.Length; i++)
    {

        char letter = buffer[i];

        letter = (char)(letter + shift);


        if (letter == ' ')
            continue;

        if (letter > 'z')
        {
            letter = (char)(letter - 26);
        }
        else if (letter < 'a')
        {
            letter = (char)(letter + 26);
        }


        buffer[i] = letter;
    }
    return new string(buffer);
}

static void Main()
{
   Console.WriteLine("Enter text to encrypt: ");
   string buffer = Console.ReadLine();
   Console.WriteLine("Enter value of shift: ");
   int shift = int.Parse(Console.ReadLine());

   string final = Caesar(buffer, shift);

   Console.WriteLine(final);
   }
}

Solution

  • If you want to skip spaces you just have to check before you transform the letter variable:

    char letter = buffer[i];
    if (letter == ' ')
        continue;
    
    letter = (char)(letter + shift);
    // ...