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

非 Y 不嫁゛ 提交于 2019-12-18 09:47:14

问题


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


回答1:


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

EDIT

Turns out that Console.ReadKey() is preferred to Console.Read().

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




回答2:


There is no way to limit the text entered into ReadLine. As the MSDN article explains,

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

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.



来源:https://stackoverflow.com/questions/3544467/how-can-i-limit-the-number-of-characters-for-a-console-input-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!