如何限制控制台输入的字符数? C#
基本上,我希望在字符开始被抑制之前,Console.ReadLine() 中最多出现 200 个字符供用户输入。除了控制台输入之外,我希望它像 TextBox.MaxLength 一样。我该怎么办呢?
我不想做 input.Substring(0, 200)。
已解决:
我使用了自己的 ReadLine 函数,它是 Console.ReadKey() 的循环。
看起来像这样,本质上是:
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();
谢谢大家
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?
And I don't want to do input.Substring(0, 200).
Solved:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无法限制输入 ReadLine 的文本。正如 MSDN 文章 所解释的那样,
您可以做的是在循环中使用 ReadKey,该循环不允许超过 200,并且如果用户键入
Environment.NewLine
则中断。There is no way to limit the text entered into ReadLine. As the MSDN article explains,
What you can do, is use ReadKey in a loop that does not allow going over 200, and breaks if the user keys
Environment.NewLine
.如果您可以使用Console.Read(),则可以循环直到达到 200 个字符或输入回车键。
编辑
事实证明,
Console.ReadKey()
优于Console.Read()
。http://msdn.microsoft.com/en-us/library/471w8d85。 ASPX
If you can use
Console.Read()
, you can loop through until you reach the 200 characters or until an enter key is entered.EDIT
Turns out that
Console.ReadKey()
is preferred toConsole.Read()
.http://msdn.microsoft.com/en-us/library/471w8d85.aspx