C#用字典中的字符键值替换字符串中的所有字符

时间:2017-03-30 20:57:05

标签: c# string encryption char

我有这本词典

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

,例如此字符串

string text = "Dad";

我想用字典键和值加密字符串!
最终加密的字符串将是:
692312

任何人都可以提供帮助吗?!

2 个答案:

答案 0 :(得分:6)

我建议使用 Linq 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()]));

更好的设计是将keys声明为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]));

修改,证明每个字符都被编码为固定长度字符串(示例中为2)&#39 ;易于解码:

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)]));

答案 1 :(得分:0)

如果您的纯文本非常大,您可能会发现使用StringBuilder而不是纯字符串连接更有效。

StringBuilder cyphertext = new StringBuilder();

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