简单的C#输出命令提示符应用程序

时间:2018-11-28 21:56:50

标签: 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”。

(循环重复) 在控制台中输入一个文本文件。

1 个答案:

答案 0 :(得分:0)

这将起作用。请查看编号注释,以查看错误所在。

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();
    }
}
相关问题