You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求完善C#摩尔斯电码翻译器:实现摩尔斯码转文本功能

Morse to Text Implementation for Your C# Project

Let's get that Morse-to-text feature up and running for your school project! You're already halfway there with the text-to-Morse code—here's how to reverse the process smoothly.

Key Ideas to Solve This

First, let's break down the problem into manageable steps:

  • Your input Morse code uses single spaces to separate letters, double spaces to separate words. We need to split the input string into these components first.
  • Instead of relying on nested for loops for lookup (which works but feels clunky), creating a Dictionary<string, char> will make matching Morse codes to characters way faster and cleaner. We can build this dictionary using your existing text and TranslatedMorse arrays by cleaning up the Morse strings first.

Modified Code with Morse-to-Text Functionality

Here's the updated version of your code with the Morse-to-text logic fully implemented:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace morse
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] text = { ' ', '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' };
            string[] TranslatedMorse = { " |", " . - |", " - . . . |", " - . - . |", " - . . |", " . |", " . . - . |" , " - - . |", " . . . . |", " . . |", " . - - - |", " - . - |", " . - . . |", " - - |", " - . |", " - - - |", " . - - . |", " - - . - |", " . - . |", " . . . |", " _ |", " . . - |", " . . . - |", " . - - |", " - . . - |", " . - - - |", " - - . . |", " . - - - - |", " . . - - - |", " . . . - - |", " . . . . - |", " . . . . . |", " - . . . . |", " - - . . . |", " - - - . . |", " - - - - . |", " - - - - - |" };

            // Build a dictionary for fast Morse-to-character lookup
            Dictionary<string, char> morseToChar = new Dictionary<string, char>();
            for (int i = 0; i < text.Length; i++)
            {
                // Clean up the Morse strings: remove leading/trailing spaces and the final '|'
                string cleanedMorse = TranslatedMorse[i].Trim().TrimEnd('|').Trim();
                morseToChar.Add(cleanedMorse, text[i]);
            }

            Console.WriteLine("Choose translation:");
            Console.WriteLine("[1] String to Morse");
            Console.WriteLine("[2] Morse to String");
            int.TryParse(Console.ReadLine(), out int selection);
            Console.WriteLine($"You've choosen: [{selection}]");
            string ToTranslate = "";
            string TranslatedText = "";

            if (selection == 1)
            {
                Console.WriteLine("Enter text:");
                ToTranslate = Console.ReadLine();
                ToTranslate = ToTranslate.ToLower();
                for (int i = 0; i < ToTranslate.Length; i++)
                {
                    for (int j = 0; j < 37; j++)
                    {
                        if (ToTranslate[i] == text[j])
                        {
                            TranslatedText += TranslatedMorse[j];
                            break;
                        }
                    }
                }
                Console.WriteLine($"Translated text: {TranslatedText}");
            }
            else if (selection == 2)
            {
                Console.WriteLine("Enter morse code using '.' or '-', split each letter by space, whole words split by two spaces");
                ToTranslate = Console.ReadLine();

                // Split input into words (double spaces separate words)
                string[] words = ToTranslate.Split(new[] { "  " }, StringSplitOptions.RemoveEmptyEntries);
                
                foreach (string word in words)
                {
                    // Split each word into individual Morse characters (single spaces separate letters)
                    string[] morseChars = word.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    
                    foreach (string morse in morseChars)
                    {
                        // Look up the Morse code safely; add '?' if invalid
                        if (morseToChar.TryGetValue(morse, out char matchedChar))
                        {
                            TranslatedText += matchedChar;
                        }
                        else
                        {
                            TranslatedText += '?';
                        }
                    }
                    // Add a space between translated words
                    TranslatedText += ' ';
                }
                // Trim the final extra space for clean output
                TranslatedText = TranslatedText.Trim();
                
                Console.WriteLine($"Translated text: {TranslatedText}");
            }
            else
            {
                Console.WriteLine("Nothing selected, program will shut down");
                System.Environment.Exit(1);
            }
        }
    }
}

What Changed?

  1. Dictionary Setup: We created a morseToChar dictionary by cleaning up your existing TranslatedMorse entries (removing extra spaces and the trailing |). This lets us look up characters in O(1) time instead of looping through arrays every time.
  2. Input Splitting:
    • First, split the input into words using double spaces as separators.
    • Then split each word into individual Morse characters using single spaces.
  3. Safe Lookup: We use TryGetValue to safely find the corresponding character—if the input has invalid Morse code, we add a ? to the output to help with debugging.
  4. Readable Output: We add spaces back between translated words to keep the output natural.

Testing Tip

Try entering something like ". - - . . ." (which should translate to "ab")—it should work smoothly! If you see ? in the output, double-check that your Morse code uses the correct spacing and characters.

内容的提问来源于stack exchange,提问作者Vít Michenka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:04:02