0

i'd appreciate if someone could help! I need to replace each character in my text(encrypted,which i read from file) with another character, which i have in my Dictionary.

 StreamReader st = new StreamReader(@"C:\path of text");
 string text = st.ReadToEnd();
 st.Close();
 char[] textChar = text.ToCharArray();  //splitting text into characters

So, in my Dictionary Dictionary<char, char> keys = new Dictionary<char,char>(); for key i have some letter, say 'n' and for value - another letter, say 'a'. So i need to replace each 'n' with 'a' in my text. Dictionary has 26 letters for keys and 26 letters for values respectively.

Now i try to replace letters and write 'decrypted' text into some file

StreamWriter sw = new StreamWriter(@"path for decrypted file");

 foreach(KeyValuePair<char, char> c in keys)
 {
    for(int i =0; i< textChar.Length; i++)
    {
         if (textChar.Contains(c.Key))
         {  //if text has char as a Key in Dictionary
             textChar[i] = keys[c.Key]; //replace with its value
         }
         else 
         {
             sw.Write(textChar[i]);  //if not, just write (in case of punctuatuons in text which i dont want to replace)
         }
     }
  }
  st.Close();
  file.Close();

This code does not work correctly, because the replacement is wrong. I'd be so grateful for any help!

4

3 回答 3

1

尝试与此类似的代码,我在没有 Visual Studio 的情况下编写了它,所以它可能需要一些更正:)

string text = File.ReadAllText(@"path for decrypted file");

foreach(var key in keys)
{
  text = text.Replace(key.Key, key.Value);
}
于 2013-01-26T13:28:02.283 回答
0

try this:

StreamReader st = new StreamReader(@"C:\path of text");
string text = st.ReadToEnd();
st.Close();

foreach(KeyValuePair<char, char> c in keys)
{
    text = text.Replace(c.Key, c.Value);
}

String.Replace returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.

Why do you use char[] textChar ? In most cases using string is preferable.

于 2013-01-26T13:26:51.067 回答
0

你的代码有问题...

如果(例如)你有一个键(a,z)和一个键(z,b)会发生什么。如果你只是应用直接交换,你所有的 a 将变成 z,然后你所有的 z 变成 b。(这意味着你所有的 a 和 z 都变成了 b)。

您需要将项目转换为一些中间值,然后您可以根据需要进行解码。

(a,z)
(z,b)

编码

(a,[26])
(z,[02])

解码

([26],z)
([02],b)
于 2013-01-26T13:32:59.533 回答