There is an
idea of
. Convert the string into an array of characters, and then define an alphabet dictionary. The key
of the dictionary is the character char
before replacement, and the value
of the dictionary is the replaced character char
. A simple implementation is written for you, and the running effect is shown in figure
.
sample code:
static void Main(string[] args)
{
var str = "Try Firefox with the bookmarks, history and passwords from another browser.";
var strArr = str.ToArray();
var result = Converter(strArr);
Console.WriteLine($":{str}");
Console.WriteLine($":{string.Join("", result)}");
Console.ReadKey();
}
public static char[] Converter(char[] originalCharArray)
{
var dict = new Dictionary<char, char> {
{ 'a','s'},
{ 'b','t'},
{'c','u'},
{'d','v'},
{'e','w'},
{'f','x'},
{'g','y'},
{'h','z'},
{'i','a'},
{'j','b'},
{'k','c'},
{'l','d'},
{'m','e'},
{'n','f'},
{'o','g'},
{'p','h'},
{'q','i'},
{'r','j'},
{'s','k'},
{'t','l'},
{'u','m'},
{'v','n'},
{'w','o'},
{'x','p'},
{'y','q'},
{'z','r'},
};
var result = new List<char>();
for (int i = 0; i < originalCharArray.Length; iPP)
{
var c = originalCharArray[i];
var isUpperCase = Char.IsUpper(c);
if (Char.IsLetter(c))
{
c = dict[Char.ToLower(c)];
if (isUpperCase)
{
c = Char.ToUpper(c);
}
}
result.Add(c);
}
return result.ToArray();
}
regular + LINQ
string str = "Try Firefox with the bookmarks, history and passwords from another browser.";
// Tjq Fajwxgp oalz lzw tggcesjck, zaklgjq sfv hskkogjvk xjge sfglzwj tjgokwj.
var dict = new Dictionary<string, string> {
{"a","s"},{"b","t"},{"c","u"},{"d","v"},{"e","w"},{"f","x"},{"g","y"},
{"h","z"},{"i","a"},{"j","b"},{"k","c"},{"l","d"},{"m","e"},{"n","f"},
{"o","g"},{"p","h"},{"q","i"},
{"r","j"},{"s","k"},{"t","l"},{"y","q"},{"z","r"}
};
var regex = new System.Text.RegularExpressions.Regex(String.Join("|", dict.Keys));
var result = regex.Replace(str, m => dict[m.Value]);