C# 如何从键盘读取字符,直到收到一个句点,并计算空格数
我对C#和OOP以及stackoverflow非常陌生。这是我的第一个场景(几个问题) 我希望用户输入字符,直到接收到句点(.)为止,并计算和报告空白的数量 我能做到这一点吗? (不确定您是否总是点击输入/返回发送) 我可以不使用字符串来执行此操作吗? (我还没有涉及字符串,这是一个自学练习,我相信解决方案应该非常简单,但我得到了不同寻常的结果) 我尝试了以下方法,但在我看到结果之前程序就关闭了,尽管我添加了C# 如何从键盘读取字符,直到收到一个句点,并计算空格数,c#,console,character,C#,Console,Character,我对C#和OOP以及stackoverflow非常陌生。这是我的第一个场景(几个问题) 我希望用户输入字符,直到接收到句点(.)为止,并计算和报告空白的数量 我能做到这一点吗? (不确定您是否总是点击输入/返回发送) 我可以不使用字符串来执行此操作吗? (我还没有涉及字符串,这是一个自学练习,我相信解决方案应该非常简单,但我得到了不同寻常的结果) 我尝试了以下方法,但在我看到结果之前程序就关闭了,尽管我添加了Console.Read()在结尾,通常有效 class CountSpaces
Console.Read()代码>在结尾,通常有效
class CountSpaces
{
static void Main(string[] args)
{
Console.WriteLine("Enter characters,finish with a period (\".\"");
char ch;
int spaces=0;
do
{
ch = (char)Console.Read();
if (ch == ' ')
{
spaces++;
}
} while (ch != '.');
Console.WriteLine("Number of spaces counted = {0}",spaces);
Console.Read();
}
}
使用Console.ReadKey()
而不是Console.Read()
Console.ReadKey()
在调用Console.ReadKey()
后,如果在两次调用之间按下了一个键,则返回
Console.Read()
以流的形式读取字符(在您的情况下根本没有用处)
要获取ReadKey
接收的char
,请使用:ch=Console.ReadKey().KeyChar代码>您想要阅读,而不是阅读
。后者只读取流中存在的下一个字符,如果不存在则返回-1,因为它不会等待(而且您可能键入的速度没有那么快!)用于获取。然后按确认键。您不需要使用字符:
int spaces = 0;
ConsoleKey key;
do
{
key = Console.ReadKey().Key;
if (key == ConsoleKey.Spacebar)
spaces++;
}
while (key != ConsoleKey.OemPeriod);
Console.WriteLine("Number of spaces counted = {0}",spaces);
请记住,NumPad上的句点键具有值ConsoleKey.Decimal
。因此,如果需要处理两个句点键,则应编写以下条件:
while (key != ConsoleKey.OemPeriod && key != ConsoleKey.Decimal);
如果您只想看到结果,只需使用ReadKey即可:
class CountSpaces
{
static void Main(string[] args)
{
Console.WriteLine("Enter characters,finish with a period (\".\"");
char ch;
int spaces = 0;
do
{
ch = (char)Console.Read();
if (ch == ' ')
{
spaces++;
}
} while (ch != '.');
Console.WriteLine("Number of spaces counted = {0}", spaces);
Console.ReadKey();
}
}
但是,如果您将程序更新为以下内容,我认为该程序会变得更有趣:
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter characters,finish with a period (\".\"");
char ch;
int spaces = 0;
do
{
ch = (char)Console.Read();
if (ch == ' ')
{
spaces++;
}
} while (ch != '.');
Console.WriteLine("Number of spaces counted = {0}", spaces);
}
}
}
我的示例使用Console.ReadKey
而不是Console.Read
:
class Program
{
static void Main(string[] args)
{
int spaces = 0;
char key;
while ((key = Console.ReadKey().KeyChar) != '.') {
if (key == ' ')
spaces++;
}
Console.WriteLine();
Console.WriteLine("Number of spaces: {0}", spaces);
Console.ReadKey();
}
}
如果我们创建从控制台创建键序列的帮助器方法:
public static IEnumerable<char> ReadKeys()
{
while (true)
{
yield return Console.ReadKey().KeyChar;
}
}
获取字符,直到获得句点,并计算空格数。您应该做的一件事是熟悉Visual Studio调试器。在线资源很多,但您可以尝试的第一件事是在一行上设置一个断点,在该行中您知道发生了什么。您可以通过点击该行上的F9,单击调试>切换断点,或单击左边距来完成此操作。您可以使用F10单步执行代码,并将鼠标悬停在变量上以查看程序中发生了什么许多关于如何实现这一点的可能有效的插图,我非常感谢(也非常惊喜!谢谢!)我想在脑海中进一步发展这一概念。var对我来说是新的(运行时类型声明?),我不太明白这将如何与其余部分相适应。。。你能提供这个想法的全面实施吗?Takewhile和Count类方法是什么?
var spaces = ReadKeys()
.TakeWhile(c => c != '.')
.Count(c => c == ' ');