简体   繁体   English

如何限制控制台输入的字符数? C#

[英]How can I limit the number of characters for a console input? C#

Basically I want 200 characters maximum to come up in Console.ReadLine() for user input before characters start being suppressed. 基本上我希望在开始抑制字符之前,在Console.ReadLine()中最多输入200个字符以供用户输入。 I want it like TextBox.MaxLength except for console input. 除了控制台输入外,我希望它像TextBox.MaxLength。 How would I go about this? 我将如何处理?

And I don't want to do input.Substring(0, 200). 而且我不想做input.Substring(0, 200).

Solved: 解决了:

I used my own ReadLine function which was a loop of Console.ReadKey(). 我使用了自己的ReadLine函数,该函数是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 感谢大家

There is no way to limit the text entered into ReadLine. 没有办法限制输入到ReadLine中的文本。 As the MSDN article explains, 正如MSDN文章所述

A line is defined as a sequence of characters followed by a carriage return (hexadecimal 0x000d), a line feed (hexadecimal 0x000a), or the value of the Environment.NewLine 行定义为字符序列,后跟回车符(十六进制0x000d),换行符(十六进制0x000a)或Environment.NewLine的值

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 . 您可以做的是在不允许超过200的循环中使用ReadKey,如果用户键入Environment.NewLine ,则会中断ReadKey。

If you can use Console.Read() , you can loop through until you reach the 200 characters or until an enter key is entered. 如果可以使用Console.Read() ,则可以循环浏览,直到达到200个字符或输入Enter键为止。

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

EDIT 编辑

Turns out that Console.ReadKey() is preferred to Console.Read() . 事实证明, Console.ReadKey()优于Console.Read()

http://msdn.microsoft.com/en-us/library/471w8d85.aspx http://msdn.microsoft.com/en-us/library/471w8d85.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM