2016-11-12 103 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