Ami*_*Tvs -1 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");
Run Code Online (Sandbox Code Playgroud)
例如这个字符串
string text = "Dad";
Run Code Online (Sandbox Code Playgroud)
我想用字典键和值加密字符串!
最终加密的字符串将是:
692312
有谁可以帮忙?!
我建议使用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()]));
Run Code Online (Sandbox Code Playgroud)
更好的设计是声明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]));
Run Code Online (Sandbox Code Playgroud)
编辑:证明每个字符都被编码为固定长度的字符串(2在示例中),它很容易解码:
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)]));
Run Code Online (Sandbox Code Playgroud)