增加foreach循环中的字符

时间:2018-01-28 05:13:34

标签: c# encryption

我试图制作一个Caesar Cipher程序,用户输入一个字符串,然后该字符串中的字符增加到3个字母,因此A变为D,依此类推使用基本的东西。

我不能在字符数组字母[i]中增加字符i,因为它是foreach迭代。我也试过使用for循环,如下所示,但我似乎无法做到正确。最初,我得到了一个像" d"这样的单一输出,但现在它崩溃了。

static void Main(string[] args)
{
  Console.WriteLine("Welcome to the Caesarian Cipher program");
  Console.WriteLine("Please, enter a word.");

  string word = Console.ReadLine();

  char[] letters = word.ToCharArray(); //chops the string up into individual characters.

// USING FOR LOOP

for(int i = 0; i < letters.Length; i++)
{
  i += 3;
  Console.WriteLine(letters[i]);
}

//USING FOREACH LOOP

  foreach(char i in letters)
  {     
     i +=3;                         // supposed to shift the alphabet by 3 steps.
     Console.WriteLine(i);          //prints the alphabet after every loop iteration.
  } 
     Console.ReadKey();
}

4 个答案:

答案 0 :(得分:2)

尝试以下代码段

static void Main(string[] args)
{
    Console.WriteLine("Welcome to the Caesarian Cipher program");
    Console.WriteLine("Please, enter a word.");

    string word = Console.ReadLine();

    char[] letters = word.ToCharArray(); //chops the string up into individual characters.

    // USING FOR LOOP
    int shift=3;
    for (int i = 0; i < letters.Length; i++)
    {
        // Letter.
        char letter = word[i];
        // Add shift to all.
        letter = (char)(letter + shift);
        // Subtract 26 on overflow.
        // Add 26 on underflow.
        if (letter > 'z')
        {
            letter = (char)(letter - 26);
        }
        else if (letter < 'a')
        {
            letter = (char)(letter + 26);
        }
        Console.WriteLine(letter);
    }

    //USING FOREACH LOOP



}

使用foreach

foreach (var c in letters)
    {

        // Add shift to all.
        char letter = (char)(c + shift);
        // Subtract 26 on overflow.
        // Add 26 on underflow.
        if (letter > 'z')
        {
            letter = (char)(letter - 26);
        }
        else if (letter < 'a')
        {
            letter = (char)(letter + 26);
        }
        Console.WriteLine(letter);
    }

答案 1 :(得分:1)

您的问题是 Increment a character in a foreach loop ,所以我回答了问题。您应该更改代码以实现算法(应该是您的挑战)。

<强> Live Demo

using System;

public class Program
{
    public static void Main(string[] args)
    {
      Console.WriteLine("Welcome to the Caesarian Cipher program");
      Console.WriteLine("Please, enter a word.");

      string word = Console.ReadLine();

      char[] letters = word.ToCharArray(); //chops the string up into individual characters.

      // For            
      for(int i = 0; i < letters.Length; i++)
      {
            var charAsInt=(int)letters[i];
            var newChar= (char)(charAsInt+3);

            Console.Write(newChar);
      }

      Console.WriteLine();

      // ForEach            
      foreach(char letter in letters)
      {
          var charAsInt=(int)letter;
          var newChar= (char)(charAsInt+3);

          Console.Write(newChar);
      }
    }
}

输出(输入abcd):

  

欢迎来到Caesarian Cipher计划

     

请输入一个单词。

     

ABCD

     

DEFG

           

DEFG

答案 2 :(得分:1)

在这种方法中,我们定义了凯撒移位规则所涵盖的字母表。这允许算法安全地容纳小写,大写,数字和其他字符,只要你将它们添加到字母表中(否则你只是依赖于ASCII排序,这有点微不足道)。

static public class ExtensionMethods
{
    static public string CaesarShift(this string input, int offset)
    {
        const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        return new string
        (
            input.Select 
            (
                c =>
                { 
                    var index = alphabet.IndexOf(c);
                    return index == -1 
                        ? c
                        : alphabet[(index + offset + alphabet.Length) % alphabet.Length];
                }

            ).ToArray()
        );
    }
}

public class Program
{

    public static void Main()
    {
        var word = "THE QUICK RED FOX JUMPS OVER THE LAZY BROWN DOG. the quick red fox jumps over the lazy brown dog. 123456789!(*&#*";

        var encoded = word.CaesarShift(3);
        Console.WriteLine(encoded);

        var decoded = encoded.CaesarShift(-3);
        Console.WriteLine(decoded);
    }
}

输出:

WKH TXLFN UHG IRa MXPSV RYHU WKH ODcb EURZQ GRJ. wkh txlfn uhg ir0 mxpsv ryhu wkh od21 eurzq grj. 456789ABC!(*&#*
THE QUICK RED FOX JUMPS OVER THE LAZY BROWN DOG. the quick red fox jumps over the lazy brown dog. 123456789!(*&#*

Run the code on DotNetFiddle

答案 3 :(得分:0)

试试这个:

static void Main(string[] args)
{
    Console.WriteLine("Welcome to the Caesarian Cipher program");
    Console.WriteLine("Please, enter a word.");

    string cypher = String.Join("", Console.ReadLine().Select(x => (char)(((x - 'a' + 3) % 26) + 'a')));
    Console.WriteLine(cypher);
}