C#用字典中字符键的值替换字符串中的所有字符 [英] C# Replace all characters in string with value of character key in dictionary
本文介绍了C#用字典中字符键的值替换字符串中的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这本字典
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
i want to encrypt the string with dictionary keys and values!
the final encrypted string will be:
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()]));
一个更好的设计是将 keys
声明为 Dictionary< char,string>
:
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]));
编辑:证明每个字符被编码为固定长度字符串(示例中为 2
)很容易解码:
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)]));
这篇关于C#用字典中字符键的值替换字符串中的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文