1

我试图让 outputLabel 成为莫尔斯电码将输出到的标签控制框。我不确定为什么只显示第一个莫尔斯电码字符而不显示其余代码。(如果我输入“cat”,我只会在 outlabel 中得到第一个莫尔斯电码字符)

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;

namespace MorseCode

{
    public partial class morseCodeForm : Form
    {
        public morseCodeForm()
        {
            InitializeComponent();
        }
        //Anthony Rosamilia
        //Make a key,value system to translate the user text. 
        //Make sure usertext appears only in lower case to minimise errors.
        private void convertButton_Click(object sender, EventArgs e)
        {
            Dictionary<char, String> morseCode = new Dictionary<char, String>()
            {
                {'a' , ".-"},{'b' , "-..."},{'c' , "-.-."}, //alpha
                {'d' , "-.."},{'e' , "."},{'f' , "..-."},
                {'g' , "--."},{'h' , "...."},{'i' , ".."},
                {'j' , ".---"},{'k' , "-.-"},{'l' , ".-.."},
                {'m' , "--"},{'n' , "-."},{'o' , "---"},
                {'p' , ".--."},{'q' , "--.-"},{'r' , ".-."},
                {'s' , ".-."},{'t' , "-"},{'u' , "..-"},
                {'v' , "...-"},{'w' , ".--"},{'x' , "-..-"},
                {'y' , "-.--"},{'z' , "--.."},
                //Numbers 
                {'0' , "-----"},{'1' , ".----"},{'2' , "..----"},{'3' , "...--"},
                {'4' , "....-"},{'5' , "....."},{'6' , "-...."},{'7' , "--..."},
                {'8' , "---.."},{'9' , "----."},
            };
            string userText = inputTextBox.Text;
            userText = userText.ToLower();
            for (int index = 0; index < userText.Length; index++)
            {
               /* if (index > 0)
                {
                    outLabel.Text = ('/').ToString();
                }
                */char t = userText[index];
                if (morseCode.ContainsKey(t))
                {
                    outLabel.Text = (morseCode[t]);
                }
            }
        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            inputTextBox.Text = "";
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
4

1 回答 1

3
outLabel.Text = (morseCode[t]);

您将 Text 属性设置为一个全新的值,而不是追加。如果该分配确实将字符串附加到已经存在的内容中,那会不会很奇怪?

您需要保留旧值:

outLabel.Text += morseCode[t];

但是,每次追加时都会创建一个新字符串。更好的解决方案;StringBuilder使用第一个(即可变字符串)构建字符串。

var sb = new StringBuilder();
for (int index = 0; index < userText.Length; index++)
{
    var t = userText[index].ToLower();
    string morseValue;

    // no need for ContainsKey/[], use a single lookup
    if (morseCode.TryGetValue(t, out morseValue))
    {
        sb.Append(morseValue);
    }
}

outLabel.Text = sb.ToString();
于 2013-10-05T01:37:26.810 回答