c# - 简单的 C# 输出命令提示符应用程序
问题描述
我目前正在研究一个接受文本文件的代码,然后显示以特定字母开头的字符数。在这里,我编写了一些代码,但无法修复我正在创建的逻辑错误。如果有人可以提供帮助,请帮助我了解我在这里做错了什么,以便我可以立即开始改进!我正在用 c# 编码并使用 Visual Studio。下面是我的代码:
static void Main(string[] args)
{
// This is loop constantly occurs
while (true)
{
string UserInput;
int count = 0;
// here I ask for user input then convert to text file.
Console.WriteLine("Enter a text file into the console.");
UserInput = Console.ReadLine();
char LastCharacter = UserInput[UserInput.Length - 1];
// Two letters I am looking for at end of text file words.
foreach (char item in UserInput)
{
if (item == 't')
{
count++;
}
else if (item == 'e')
{
count++;
}
}
Console.WriteLine("There are {0}", + count + " words that end in t or e.");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
这是我在命令提示符下得到的输出。
Enter a text file into the console.
//Entered user text
that is the way
Result:
There are 2 words that end in t or e.
Press any key to continue...
注意,它只计算单词开头的 t。我很难更改该设置,因此它计算单词末尾的“e”和“t”。
(循环重复)在控制台中输入一个文本文件。
解决方案
这将起作用。请查看编号的评论以了解您在哪里出错。
static void Main(string[] args)
{
while (true)
{
// This is loop constantly occurs.
//variables;
string UserInput;
int count = 0;
//Where I ask for user inout then convert to text file.
Console.WriteLine("Enter a text file into the console.");
UserInput = Console.ReadLine();
char LastCharacter = UserInput[UserInput.Length - 1];
// 1) You need to extract the words in the user input - this assumes they are delimited by a space
foreach (var word in UserInput.Split(' '))
{
// 2) You want to check the first character of each word
// 3) The StringComparison.CurrentCultureIgnoreCase assumes you want to ignore case - if you DO want to consider case, remove the parm
// 4) You can do the compare using the 'or' operator - no need for else if
if (word.StartsWith("t", StringComparison.CurrentCultureIgnoreCase) || word.StartsWith("e", StringComparison.CurrentCultureIgnoreCase))
{
count++;
}
}
Console.WriteLine("There are {0}", +count + " words that begin with t or e.");
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
推荐阅读
- javascript - 具有唯一 URL 的 Flask 站点上的动态加载
- python - 使用 bs4 解析 utf-8 编码页面中的特殊字符的问题
- c++ - 如何使用参数初始化作为模板参数给出的类
- python - 第一次迭代后内部 for 循环被忽略,外部 for 循环工作得很好
- typescript - 打字稿:如何键入具有不同类型的未知大小的元组?
- laravel - 用于子域 API 的 Laravel CORS
- css - 覆盖 CSS 问题
- mysql - 在 MySQL 中查找可用的预约空档
- javascript - 渲染 Next.js 没有返回任何内容
- java - 从 Java 8 更新到 Java 11 时找不到 java.sql.Connection 的类文件错误