2016-11-12 139 views
0

我的項目:基本上,我在研討會上寫了一個小型加密程序,它接受用戶輸入並檢查循環中的字符位置是否均勻,如果是這樣,它將位於字符串,否則結束。它看起來像這樣;C#在循環中操縱字符串

string userInput = "", encodedInput = "", evenChar = "", oddChar = ""; 
int charCount = 0; 

Console.WriteLine("Input your text: "); 
userInput = Console.ReadLine(); 

foreach(char character in userInput) 
{ 
    charCount++; 
    if ((charCount % 2) == 0) 
    { 
     evenChar = evenChar + character; 
    } 
    else 
    { 
     oddChar = character + oddChar; 
    } 
    encodedInput = evenChar + oddChar; 
} 
Console.WriteLine(encodedInput); 

現在這工作正常,當我輸入「你好,我的名字是傑夫!」我得到「im aei ef!fjs mny h」。

現在我正在嘗試編寫一個解密循環。我選擇解密的方法基本上是將字符串中的最後一個字符添加到一個新的空字符串中,然後從字符串中取出第一個字符,並將它添加到同一個空字符串中,然後簡單地遞減加密的總長度字符串並增加第一個字符的位置。

char lastChar = ' '; 
char firstChar = ' '; 
StringBuilder decodedInput = new StringBuilder(); 

int len = encodedInput.Length; 
int len2 = 0; 

foreach(char character in encodedInput) 
{ 
    lastChar = encodedInput[len - 1]; 
    decodedInput.Append(lastChar.ToString()); 
    len--; 

    firstChar = encodedInput[len2]; 
    len2++; 
    decodedInput.Append(firstChar.ToString()); 
} 

Console.WriteLine(decodedInput.ToString()); 

現在這項工作大部分工作正常。它採用相同的「im aei ef!fjs mny h」並輸出「你好我的名字是jeff !! ffej si eman ym ih」。它反映的字符串,因爲我產生的每個循環字符,所以「你好我的名字是傑夫」變成36個字符。我試過把這個循環減半,但你仍然有一些鏡像。

我很清楚,有更好或更簡單的方法來破譯這個,但我想這樣做是爲了教育目的。

親切的問候,

Vocaloidas。

+0

你可以用容量使用StringBuilder(更好的性能)(userInput/2)的evenchar和容量(userInput/2 + 1)用於加密部分中的奇數字符變量。另外encodeInput = evenChar + oddChar;應該在foreach循環之後。 –

回答

3

不要遍歷編碼輸入的每個字符,因爲您最終會處理每個字符兩次。您已經計數向上和向下與lenlen2變量字符串,因此,如果您更換foreach有:

while (len > len2) 

這隻會處理字符串的每個字符一次

你將不得不做一些當字符串是奇數字符時處理中間字符 - 即當lenlen2相等時。爲此添加如下內容:

  if (len == len2) 
       break; 

在循環中,使之成爲:

 while (len > len2) 
     { 
      lastChar = encodedInput[len - 1]; 
      decodedInput.Append(lastChar.ToString()); 
      len--; 

      if (len == len2) 
       break; 

      firstChar = encodedInput[len2]; 
      len2++; 
      decodedInput.Append(firstChar.ToString()); 
     } 
+0

你真了不起:) – Vocaloidas