【问题标题】:Why is my code outputting the original string value and the converted string value rather than just the converted string value?为什么我的代码输出的是原始字符串值和转换后的字符串值,而不仅仅是转换后的字符串值?
【发布时间】:2020-02-22 22:22:11
【问题描述】:
string userInput = stringInput.Text;
string userSentence = userInput.ToLower();

foreach (char letter in userSentence)
{
    var sentence = morseCodeTable.FirstOrDefault(x => x.Key == letter.ToString()).Value ?? " / ";
    userSentence += sentence;
}

stringInput.Text = userSentence;

【问题讨论】:

  • 因为您将userSentence 初始化为用户的输入,然后继续将莫尔斯电码附加到该输入。你可能想要string userInput = stringInput.ToLower();string userSentence = ""

标签: c# loops foreach


【解决方案1】:

问题出在这里:

   userSentence += sentence;

您将每个已加密的字符 sentence 附加到 userSentence

然后您将userSentence 返回到表单。

也许会这样

string userInput = stringInput.Text;
string userSentence = userInput.ToLower();
string encryptedSentence = "";

foreach (char letter in userSentence)
{
    var morseChar = morseCodeTable.FirstOrDefault(x => x.Key == letter.ToString()).Value ?? " / ";
    encryptedSentence += morseChar;
}

stringInput.Text = encryptedSentence;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2011-12-18
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多