C# 反转foreach循环动作
我想将每个字符串转换/查找为int并反转此操作。 我设法做了第一部分,但第二部分给了我一些问题C# 反转foreach循环动作,c#,wpf,foreach,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);
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);
谢谢 这将不能按原样工作,因为您将数字添加到一个没有填充的字符串中 让我们假设前三个字母的值是'1','2','3',您将得到一个带123的字符串。 现在,如果你知道每个字母的长度是1整数,你就很好了,但是如果12是有效的,会发生什么呢?23岁 在你的例子中,这可能不是一个真正的问题,因为值可能都是2整数长的,但是它非常缺乏,除非它是家庭作业,在这种情况下,哦,好吧 字母表的ascii值将从A的65变为z的122
你可以填充它们,比如说每个数字3个字符,所以A是065,等等,给它们划界,然后在上面拆分字符串,使用一个数组,如shahar的建议、列表等…根据我上面的建议,这里有一个固定的程序
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);
在您的场景中,加密可能会像您预期的那样提供输出,但是使用这种机制很难解密加密的文本。所以我只是对你的代码做了一些定制,让它在这里可行 我建议在这里使用类似的方法:
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;
}
代码不起作用的原因:
您已将encrypt声明为string并遍历该字符串值中的每个整数,这是不可能的。
如果使该循环再次遍历该字符串值中的每个字符,则会产生混淆。作为:
让我们将S作为您的输入。它的等效int值是114,所以如果你做一个循环,意味着它将给出1,1,4,你将不会从中得到s。
不,这是不可逆的。这对ex 12345意味着什么?123和45还是12和345?你不能这样做,因为每个字符都会变成一个有两个或三个数字的数字。尝试使用数组来存储转换后的字符,以便将它们转换回stringLet(假设输入为“A”)。然后将字符“A”转换为值65。然后你打电话给我,继续。所以现在加密一个字符串。然后在encrypt 6中循环每个字符,然后在encrypt 5中循环,并将其转换为字符-而不是使用'65'并将其转换为字符。看看asciitable.com——你所做的一切都没有意义。让我们更广泛地了解你想要实现的目标。这是正确的答案。基本问题是假设int x=int c;字符串s=x.ToString;仅向加密字符串添加一个字符。