如何限制控制台输入的字符数? 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();
感谢大家
如果您可以使用Console.Read()
,则可以循环直到达到200个字符或直到输入回车键。
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); }
编辑
事实certificate, Console.ReadKey()
比Console.Read()
更Console.Read()
。
无法限制输入ReadLine的文本。 正如MSDN文章所解释的那样,
一行被定义为一个字符序列,后跟一个回车符(hex0x000d),换行符(hex0x000a)或
Environment.NewLine
的值
你可以做的是,在一个不允许超过200的循环中使用ReadKey,如果用户键入Environment.NewLine
则中断。