2016-08-23 36 views
-2

我想将字符串中的字符移位20来匹配我在basic中使用的文件格式。我使用下面的代码在C#需要在c#中做一个ascii移位密码#

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace test_controls 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
     public string text3; 
     private void button1_Click(object sender, EventArgs e) 
     { 
      // This is a test conversion of my pdw save routine from basic to c# 
     int pos = 0; 
     string text = label1.Text; 
     int t = text.Length;  // get the length of the text 
     while (pos < t + 1) ; 
     string s = text.Substring(pos, 1); // get subsstring 1 character at a time 

     byte[] ASCIIValues = Encoding.ASCII.GetBytes(text); // convert that character to ascii 
     foreach (byte b in ASCIIValues) 
     { 
      int temp = b; 
      temp = temp + 20; // add 20 to the ascii value 
      char text2 = Convert.ToChar(temp); // convert the acii back into a char 
      text3 =""+ text2.ToString(); // add the char to the final string 

     } 
     label1.Text = text3; // rewrite the new string to replace the old one for the label1.text 
    } 

} 

}

问题是,它只是什么也不做,不回应,我要告诉窗口关闭无响应程序。要清楚,我使用C#中的winforms来制作一个转换密码。我使用的所有这些代码都在各种答案中找到,并将它们拼凑在一起。在Vb或任何其他基本的,我只是得到字符串中的每个字符的ascii值,然后做数学并使用chr $命令将其转换回来。

任何帮助将不胜感激。

+9

'while(pos Cameron

+1

做“temp = temp + 20”是不正确的,因为它会导致你的许多字母不再是字母。例如,如果您正在进行2的移位,您希望“z”映射到“b”,这将需要减法(不是加法)。在这个例子中,请注意z = 122和122 + 20 = 142,它甚至不再是有效的ASCII字符。 – EJoshuaS

+0

我只想将值返回到一个字符并返回到一个字符串中,而不管它变成什么字符。在我的文件格式中,由于加20,空间甚至变成了不同的字符,因此得到的字符串没有空格。然后,我会根据需要反转该过程,以便以加密格式保存和加载。我想知道在一点上它不是一个无限循环。唯一的原因是我这样编码是因为在基本上我使用了一个下一个循环,所以我认为时间会一直处理,直到字符串结束。 – Larryrl

回答

0

你有两个问题。正如在评论中指出,下面一行是一个无限循环:

while (pos < t + 1) ; 

即使没有循环,但是,你的漂移算法不正确。下面的行,也将导致不正确的结果:

temp = temp + 20; 

考虑作为反例在下列情况下:

  • ģ映射到[
  • ASCII Z = 122 122 + 20 = 144,这甚至不是有效的ASCII字符。
  • 大写字母Z将映射为小写字母n 您可以想出其他类似的情况。

顺便说一句,你也可以将这一行改写为temp += 20

最后,这条线是不正确的:

text3 =""+ text2.ToString(); 

你没有追加新的文本文字3,你每次你做一个迭代时间更换,所以文字3将始终包含的最后一个字符编码(而不是整个字符串)。请记住,像这样构建一个C#字符串(尤其是长整数)效率不高,因为字符串是C#中的不可变对象。如果有问题的字符串可能会很长,您可以考虑使用StringBuilder来达到此目的。