反转foreach循环动作

时间:2015-08-23 09:39:00

标签: c# wpf foreach

我想将每个字符串转换/找到(int)并反转此操作。 我设法做了第一部分,但第二部分给了我一些问题。

string input;
string encrypt = ""; string decrypt = "";

input = textBox.Text;
foreach (char c in input)
{
    int x = (int)c;
    string s = x.ToString();
    encrypt += s;
}
MessageBox.Show(encrypt);

foreach (int i in encrypt)
{
    char c = (char)i;
    string s = c.ToString();
    decrypt += c;
}
MessageBox.Show(decrypt);

谢谢!

3 个答案:

答案 0 :(得分:2)

根据我上面的建议,这是一个固定的程序

        string encrypt = ""; string decrypt = "";

        string input = Console.ReadLine();
        var length = input.Length;
        int[] converted = new int[length];
        for (int index = 0; index < length; index++)
        {
            int x = input[index];
            string s = x.ToString();
            encrypt += s;
            converted[index] = x;
        }

        Console.WriteLine(encrypt);
        for (int index = 0; index < converted.Length; index++)
        {
            char c = (char)converted[index];
            string s = c.ToString();
            decrypt += s;
        }
        Console.WriteLine(decrypt);

答案 1 :(得分:1)

这不会按原样运行,因为您正在为没有填充的字符串添加数字。

我们假设前三个字母的值是&#39; 1&#39;&#39; 2&#39;&#39; 3&#39;,你&#39;将有一个带有&#34; 123&#34;的字符串。 现在,如果你知道每个字母都是1个长度,那么你很好,但如果12有效会怎么样?和23?

这可能不是真实的&#34;在你的情况下出现问题,因为价值可能都是2英镑长,但它非常缺乏(除非它的作业,在这种情况下,哦,好吧......)

字母表的ascii值将从https://developers.google.com/beacons/proximity/reference/rest/v1beta1/beacons/register的65变为122 A

你可以填充它们(比如说每个数字3个字符,{0}代表{0}},依此类推),分隔它们(有&#34;。&#34;,并在其上分割字符串) ,使用数组(如shahar的建议),列表等等......

答案 2 :(得分:1)

在您的方案中,加密可能会按预期提供输出,但很难使用此类机制解密加密文本。所以我只是对你的代码做一些自定义,并使它在这里可行。

我在这里建议类似的一个:

Z

您的代码无效的原因:

  1. 您已将 string input; string encrypt = ""; string decrypt = ""; int charCount = 0; input = "textBox.Text"; foreach (char c in input) { int x = (int)c; string s = x.ToString("000"); encrypt += s; charCount++; } // MessageBox.Show(encrypt); while (encrypt.Length > 0) { int item = Int32.Parse(encrypt.Substring(0, 3)); encrypt = encrypt.Substring(3); char c = (char)item; string s = c.ToString(); decrypt += c; } 声明为字符串并遍历该字符串值中的每个整数,但它很安静。
  2. 如果您使该循环再次遍历该字符串值中的每个字符,则会产生混淆。如: 我们以encrypt为输入。它的等效int值是S所以如果你做一个循环意味着它会给11411,你就不会从中获得4