非常谨慎,这是家庭作业。无论如何试图做一个莫尔斯电码转换器,我只是停留在最后一个问题上。我想使用字符,然后使用string.replace,但是我不能,因为我的字典都是字符串。我想用字符。那我该如何解决呢?
[√] Flutter (Channel beta, v0.4.4, on Microsoft Windows [Version 10.0.17134.112], locale en-GB)
• Flutter version 0.4.4 at C:\Program Files\flutter
• Framework revision f9bb4289e9 (6 weeks ago), 2018-05-11 21:44:54 -0700
• Engine revision 06afdfe54e
• Dart version 2.0.0-dev.54.0.flutter-46ab040e58
[√] Android toolchain - develop for Android devices (Android SDK 27.0.3)
• Android SDK at C:\Users\ritar\AppData\Local\Android\sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-27, build-tools 27.0.3
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
• All Android licenses accepted.
[√] Android Studio (version 3.1)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 24.1.1
• Dart plugin version 173.4700
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b02)
[√] Connected devices (1 available)
• 601SO • CB512BVV00 • android-arm64 • Android 7.0 (API 24)
答案 0 :(得分:1)
替换将字符串/字符作为参数,而不是键或值的集合。
在这种情况下,您甚至不需要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;
答案 1 :(得分:0)
好吧,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]);