如何限制字符的控制台输入多少? C# [英] How can I limit the number of characters for a console input? C#
问题描述
基本上我想最多200个字符来在到Console.ReadLine()供用户输入开始被抑制的字符之前。我希望它像TextBox.MaxLength除了控制台输入。我怎么会去吗?
Basically I want 200 characters maximum to come up in Console.ReadLine() for user input before characters start being suppressed. I want it like TextBox.MaxLength except for console input. How would I go about this?
和我不想做 input.Substring(0,200)。
解决:
我用我自己的ReadLine功能,它是一个。Console.ReadKey()的循环
I used my own ReadLine function which was a loop of Console.ReadKey().
它看起来像这样,基本上是:
It looks like this, essentially:
StringBuilder sb = new StringBuilder();
bool loop = true;
while (loop)
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true); // won't show up in console
switch (keyInfo.Key)
{
case ConsoleKey.Enter:
{
loop = false;
break;
}
default:
{
if (sb.Length < 200)
{
sb.Append(keyInfo.KeyChar);
Console.Write(keyInfo.KeyChar);
}
break;
}
}
}
return sb.ToString();
谢谢大家。
Thanks everyone
推荐答案
如果你可以使用 Console.Read()
,你可以遍历,直到达到200个字符,或者直到输入了回车键。
If you can use Console.Read()
, you can loop through until you reach the 200 characters or until an enter key is entered.
StringBuilder sb = new StringBuilder();
int i, count = 0;
while ((i = Console.Read()) != 13) // 13 = enter key (or other breaking condition)
{
if (++count > 200) break;
sb.Append ((char)i);
}
修改
原来, Console.ReadKey()
最好 Console.Read()
。
的http:// msdn.microsoft.com/en-us/library/471w8d85.aspx
这篇关于如何限制字符的控制台输入多少? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!