2016-08-23 18 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來達到此目的。