Ryan Easter
Ryan Easter

Reputation: 45

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);
   }
}

Upvotes: 2

Views: 1841

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

You should encrypt if and only if you know how to do it (i.e. if you have a a..z or A..Z character); in case you have different character (space, minus sign, quotation mark, whatever), just leave it intact:

using System.Linq;

...

static string Caesar(string value, int shift) {
  //DONE: do not forget about validation
  if (null == value)
    return value; // or throw exception (ArgumentNullValue)

  int n = 'z' - 'a' + 1;

  // For each character in the value we have three cases:
  //   a..z letters - encrypt
  //   A..Z letters - encrypt
  //  other letters - leave intact
  //  "n + shift % n) % n" - let's support arbitrary shifts, e.g. 2017, -12345 etc. 
  return string.Concat(value
    .Select(c => 
        c >= 'a' && c <= 'z' ? (char) ('a' + (c - 'a' + n + shift % n) % n) 
      : c >= 'A' && c <= 'Z' ? (char) ('A' + (c - 'A' + n + shift % n) % n) 
      : c));
}

Test:

Console.Write(Caesar("Hello! It's a test for so called 'Caesar cipher'.", -2));

Outcome (please, notice that spaces, apostrophes, exclamation mark are left as they were):

Fcjjm! Gr'q y rcqr dmp qm ayjjcb 'Aycqyp agnfcp'.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

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);
// ...

Upvotes: 2

Related Questions