检查按下的键,然后将其添加到String

时间:2017-04-10 16:09:14

标签: c# string console

我正在编码,我对c#有疑问。我有以下代码:

    if (Console.ReadKey(true).KeyChar.ToString() == "l") // Reading single key in console
            goto load; 
// If not, continue

// Here, if I didn't press "l", I have to press the key once more, because at first, it checked it in if statement above so it is reding this into the string on the second time. So just want that if I didn't press "l" Automatically add that key to string below
            string read = Console.ReadLine();

问题是,如果我不想按“l”第一个字母,我必须再按2次。 (因为第一次按下是检查Console.ReadKey()。) 那么,如果我按下不同的键而不是“l”,它怎么能自动将它写入下面的Console.ReadLine呢?感谢

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是将第一个字符捕获到变量中,这样您就可以将其保存以供日后使用,以防它不是您要查找的字符。另请注意,如果我们希望输出显示在控制台窗口中,我们就不会将true传递给ReadKey()方法。

如果输入不是您要查找的输入,则可以将Console.ReadLine()的结果保存到另一个变量中,并将原始字符添加到其开头:

// First capture the character into a variable, so we can save it for later
var firstChar = Console.ReadKey().KeyChar.ToString();

if (firstChar == "l")
{
    // Do something here, or call another method,
    // But don't GOTO anywhere.
    Console.WriteLine("You pressed 'l'");
}
else
{
    // If they didn't press 'L', then we take the saved character and
    // Add it to the beginning of the rest of the user input:
    var restOfInput = firstChar + Console.ReadLine();

    Console.WriteLine($"You entered the text: {restOfInput}");
}