摩尔斯电码转换器只输出一个字符c#

时间:2013-10-05 01:35:12

标签: c#

我试图让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();
        }
    }
}

1 个答案:

答案 0 :(得分:3)

outLabel.Text = (morseCode[t]);

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

您需要保留旧值:

outLabel.Text += morseCode[t];

然而,每次追加时都会创建一个 new 字符串。更好的解决首先使用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();