【问题标题】:C# Ascii conversion and backC# Ascii 转换和返回
【发布时间】:2014-10-11 08:04:30
【问题描述】:

好的,所以我制作了一个基本的停止者加密程序,它将每个字符偏移给定数量,这是通过使用字符 ASCII 密钥然后将应该偏移的数量添加到密钥来完成的。

基本上我可以看到为什么我的程序不工作并且没有返回我希望它返回的字符串,这里是加密的伪代码:

 `Type in text
  Type in encryption key
     Display Encrypt(text, key)
        function Encrypt(text,key)
          For each letter in text
            Get its ascii code
              add the key to the ascii code
                  Turn this new ascii code back to a character
                      Append character to ciphertext string

结束 返回密文`

第一个输入是句子,第二个输入是要偏移的数字

这是我的 C# 代码:

static void Main(string[] args)
    {
        Console.WriteLine("Write a Sentance!");
        string text = Console.ReadLine();
        Console.WriteLine("How many characters do you want to ofset it by?");
        int key = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(encrypt(text,key));
        Console.ReadLine();

    }

    static string encrypt(string text, int key)
    {
        string ciphertext = "";
        int y = 0;
        char[] letters = text.ToCharArray();
        for(int x = 0; x <= letters.Length; x++)
        {
            int AsciiLET = (int)letters[y];
            string Asciiletter = (AsciiLET + key).ToString();
            ciphertext += Asciiletter;
            y++;  
        }
        return ciphertext;

    }

【问题讨论】:

  • “我知道为什么我的程序不工作”告诉我们原因。还要发布一些预期的输入和输出。
  • 你不使用key。那是怎么回事?
  • 这段代码会抛出错误,请注意最好将错误放在以后的问题中。

标签: c# arrays string char ascii


【解决方案1】:

有几处不对:

  1. 只能转到.Length 之前的一个。即&lt; 不是&lt;=
  2. x 不是 yy 已删除
  3. ToString 在数字上 ((AsciiLET + key)),给你一个字符串中的数字,例如 "89"
  4. 使用key

现在看起来像:

static string encrypt(string text, int key)
{
    string ciphertext = "";
    char[] letters = text.ToCharArray();
    for (int x = 0; x < letters.Length; x++) // see 1
    {
        int AsciiLET = (int)letters[x]; //2
        char Asciiletter = (char)(AsciiLET + key); //3 & 4
        ciphertext += Asciiletter;
    }
    return ciphertext;
}

【讨论】:

  • 太好了,多谢了,你有没有机会快速解释一下分配 Asciiletter 的那行是做什么的?
  • @user3063533 就像您将char 转换为上方的int 一样,这将从int 转换回char
  • 非常感谢朋友,我会支持你,但我需要更多的声誉,所以我不能。
  • 没问题,我已经给你投了赞成票,以帮助你的代表情况!
猜你喜欢
  • 2021-01-20
  • 2011-04-10
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多