2013-10-05 269 views
1

我想让outputLabel成为一个标签控制框,莫尔斯电码将输出到。我不确定为什么只显示第一个莫尔斯电码字符,但不显示其余的代码。 (如果我输入“猫”我只得到outlabel第一莫尔斯电码字符)莫尔斯电码转换器只输出一个字符c#

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(); 
     } 
    } 
} 

回答

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(); 
+0

+1。附注:由于没有大/小写摩尔斯电码,'ToLower'可能会有用。 –

+0

这是完美的。我感谢你的速度和多个答案。我会一直尝试更有效的路径。 – Adreamer82

+0

@AlexeiLevenkov:Good call –