C# Replace all characters in string with value of character key in dictionary

六眼飞鱼酱① 提交于 2021-02-08 11:35:09

问题


hi i have this dictionary

Dictionary<char, string> keys = new Dictionary<char, string>();
keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");

and for example this string

string text = "Dad";

i want to encrypt the string with dictionary keys and values!
the final encrypted string will be:
692312

anyone can help?!


回答1:


I suggest using Linq and string.Concat:

// Dictionary<string, string> - actual keys are strings
Dictionary<string, string> keys = new Dictionary<string, string>();

keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");

string result = string.Concat(text.Select(c => keys[c.ToString()]));

a better design is to declare keys as Dictionary<char, string>:

Dictionary<char, string> keys = new Dictionary<char, string>() {
  {'a', "23"},
  {'A', "95"},
  {'d', "12"},
  {'D', "69"},    
};

...

string result = string.Concat(text.Select(c => keys[c]));

Edit: proving that each character is encoded as a fixed length string (2 in the example) it's easy to decode:

Dictionary<string, char> decode = keys
  .ToDictionary(pair => pair.Value, pair => pair.Key);

int fixedSize = decode.First().Key.Length;

string decoded = string.Concat(Enumerable
  .Range(0, result.Length / fixedSize)
  .Select(i => decode[result.Substring(i * fixedSize, fixedSize)]));



回答2:


If your plaintext is quite large, you might also find it more performant to use a StringBuilder, instead of plain string concatenation.

StringBuilder cyphertext = new StringBuilder();

foreach(char letter in text)
{
    cyphertext.Append(keys[letter]);
}


来源:https://stackoverflow.com/questions/43128170/c-sharp-replace-all-characters-in-string-with-value-of-character-key-in-dictiona

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!