从凯撒密码 c# 中的字符串中删除空格的问题

Issue with removing spaces from string in caesar cipher c#

我正在尝试制作凯撒密码程序,但我无法从最终加密输出中删除空格。我用过:

if (letter == ' ')
                continue;

但这似乎不起作用,我无法确定导致问题的原因。我使用 C# 的时间并不长,所以这可能是一个愚蠢的错误。

如果我要输入偏移量为 7 的短语:"I need help",则以下输出将是 pAullkAolsw,所有空格都变为大写 A。我希望得到的输出应该在示例中:p ullk olsw.

下面是我的完整代码:

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

如果你想跳过空格你只需要检查 before 你转换字母变量:

char letter = buffer[i];
if (letter == ' ')
    continue;

letter = (char)(letter + shift);
// ...

当且仅当您知道如何加密(即如果您有 a..zA..Z 字符)时,您才应该加密;如果您有不同的字符(space、减号、引号等),只需保持原样:

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

测试:

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

结果(请注意 spaces撇号感叹号 保持原样):

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