简体   繁体   中英

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

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?!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM