如何使用字符串.replace()与字符?



所以完全是家庭作业。无论如何,尝试制作一个莫尔斯电码转换器,我只是停留在最后一个问题上。我想使用字符,然后使用string.replace 但我不能,因为我的字典都是字符串。不过我想使用字符。那么我将如何解决这个问题呢?

public void InputReader()
{
string inputForTranslating = inputForTranslator.Text;
Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "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", "--.." }
};
char[] charArray = inputForTranslating.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
outPutTranslation.Text = outPutTranslation.ToString().Replace(morseDictionary.Keys, morseDictionary.Values); ////This is where the error occurs "cannot convert from 'System.Collections.Generic.Dictionary<string, string>.KeyCollection' to 'char'"
}
}

替换将字符串/字符作为参数,而不是键或值的集合。 在这种情况下,您甚至不需要Replace,您只需根据键添加值即可。
此外,您的outPutTranslation.Text将只有最后一个字符。

Dictionary<string, string> morseDictionary = new Dictionary<string, string>
{
{ " ", " " }, { ",", "--..--" }, { ".", ".-.-.-" }, { "\?", "..--.." }, { "0", "-----" }, { "1", ".----" }, { "2", "..---" }, { "3", "...--" },
{ "4", "....-" }, { "5", "....." }, { "6", "-...." }, { "7", "--..." }, { "8", "---.." }, { "9", "----." }, { "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", "--.." }
};
string output = "";
foreach (char c in inputForTranslating.ToCharArray())
{
output += morseDictionary[c];
}
outPutTranslation.Text = output;

好吧,string.Replace()两个字符或两个字符串都有效。该错误清楚地表明morseDictionary.Keys不是字符串。也不是morseDictionary.Values.没错,它们是字典的键和值列表!

该代码中还有另一个错误。您正在将输入转换为 char 数组,然后迭代每个字符,并尝试替换该字符。想想它在做什么:

如果你有-.-,在第一次迭代中,你将搜索-,第二次搜索.,最后搜索-。你永远找不到K

您应该迭代字典,并搜索整个字符串中的每个单词。

foreach(string key in morseDictionary) {     
//for morse->letter   
inputForTranslating=inputForTranslating.Replace(morseDictionary[key],key);
//for letter->morse
inputForTranslating=inputForTranslating.Replace(key,morseDictionary[key]);

最新更新