如果是我,我会保留每个字符的字典映射及其对应的莫尔斯字符串。这将使来回转换变得容易。
例如:
private static Dictionary<char, string> MorseMap = new Dictionary<char, string>
{
{'A', ".-"}, {'B', "-..."}, {'C', "-.-."}, {'D', "-.."},
{'E', "."}, {'F', "..-."}, {'G', "--."}, {'H', "...."},
{'I', ".."}, {'J', ".---"}, {'K', "-.-"}, {'L', ".-.."},
{'M', "--"}, {'N', "-."}, {'O', "---"}, {'P', ".--."},
{'Q', "--.-"}, {'R', ".-."}, {'S', "..."}, {'T', "-"},
{'U', "..-"}, {'V', "...-"}, {'W', ".--"}, {'X', "-..-"},
{'Y', "-.--"}, {'Z', "--.."},{'1', ".----"}, {'2', "..---"},
{'3', "...--"}, {'4', "....-"},{'5', "....."}, {'6', "-...."},
{'7', "--..."}, {'8', "---.."},{'9', "----."}, {'0', "-----"},
{'.', ".-.-.-"}, {',', "--..--"},{'?', "..--.."}, {'\'', ".----."},
{'!', "-.-.--"}, {'/', "-..-."},{'(', "-.--."}, {')', "-.--.-"},
{'&', ".-..."}, {':', "---..."},{';', "-.-.-."}, {'=', "-...-"},
{'+', ".-.-."}, {'-', "-....-"},{'_', "..--.-"}, {'"', ".-..-."},
{'$', "...-..-"}, {'@', ".--.-."}
};
现在,使用此映射中的键和值,很容易编码和解码为莫尔斯电码:
private static string ConvertToMorse(string input)
{
var morse = new StringBuilder();
foreach (var character in input)
{
var upperCaseChar = char.ToUpper(character);
if (MorseMap.ContainsKey(upperCaseChar))
{
morse.Append(MorseMap[upperCaseChar]);
}
else
{
// If there's no mapping for this character, just add it
morse.Append(character);
}
// Add a space between each morse string.
morse.Append(' ');
}
return morse.ToString().Trim();
}
private static string ConvertToAlpha(string morse)
{
var alpha = new StringBuilder();
// Split words on double-spaces so we can add single spaces back where needed
var morseCodeWords = morse.Split(new[] {" "}, StringSplitOptions.None);
foreach (var morseCodeWord in morseCodeWords)
{
var morseCodeStrings = morseCodeWord.Split(' ');
foreach (var morseCodeString in morseCodeStrings)
{
if (MorseMap.ContainsValue(morseCodeString))
{
alpha.Append(MorseMap.First(item => item.Value == morseCodeString).Key);
}
else
{
// If there's no mapping for the string, just add it
alpha.Append(morseCodeString);
}
}
// Add a space between each word
alpha.Append(' ');
}
return alpha.ToString();
}
使用示例:
private static void Main()
{
var test = "This is my test string.";
var morseVersion = ConvertToMorse(test);
var alphaVersion = ConvertToAlpha(morseVersion);
Console.WriteLine("Original string ... {0}", test);
Console.WriteLine("Morse version ..... {0}", morseVersion);
Console.WriteLine("Alpha version ..... {0}", alphaVersion);
}