Amir Tvs
Amir Tvs

Reputation: 85

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

Upvotes: 0

Views: 1675

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

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

Upvotes: 6

siboc
siboc

Reputation: 66

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

Upvotes: 0

Related Questions