0

我的任务是创建 ac# 控制台文本分析程序。该程序允许用户逐字输入句子单句号是句子的结尾双句号是打破循环并给出文本分析

我有正确计算单词和句子的程序。

我的问题是:如何更改我的代码,以便程序不会将句号计为一个字符?

以下是我到目前为止的代码

 case "1":

    string UserSentence="";
    string newString="";
    string UserWord;
    int SentenceCount=1;
    int WordCount=0;
    double CharCount=0;

    Console.WriteLine("You have chosen to type in your sentance(s) for analysis.\nPlease input each word then press enter.\n\nUse one full stop to end the sentence.\nUse two full stops to finish inputting sentences");
    while (true)
        {
            UserWord = Console.ReadLine();
            WordCount++;
            UserSentence = UserSentence+UserWord;


                if (UserWord == "..")
                    {
                        CharCount=CharCount-2;
                        WordCount--;
                        break;
                    }

                if (UserWord == ".")
                    {
                        CharCount=CharCount-1;
                        WordCount--;
                        SentenceCount++;
                    }
        }

    foreach (char c in UserSentence)

        {
            if (c ==' ')
            continue;
            newString += c;
        }
        CharCount = newString.Length;
        Console.WriteLine("Their are {0} characters",CharCount);
        Console.WriteLine("Their are {0} Sentences",SentenceCount);
        Console.WriteLine("Their are {0} Words",WordCount);
    break;

我试图通过根据句号的数量减去 2 或 1 来纠正字符数,但是它不起作用

感谢您提前提供任何帮助。

4

3 回答 3

1

在这里,您只是覆盖了 的值CharCount,丢弃了您之前所做的所有减法:

CharCount = newString.Length;

可以改为:

CharCount = CharCount + newString.Length;

为了给出正确的结果。

还有其他选项,例如计算句子中的数量,.在获得长度之前将句子中的所有内容替换.为空字符串等等。

样式注意事项:在 C# 中,局部变量通常是 camelCase,而不是 PascalCase。

于 2012-12-02T21:25:31.790 回答
0

您可以使用 LINQ 来计算不是空格或点的字符。

int characterCount = s.Count(x => x != ' ' && x != '.');
于 2012-12-02T21:28:20.237 回答
0

您可以只计算不是“。”的字符。

CharCount = newString.Where(c => !c.Equals('.') && !c.Equals(' ')).Count();
于 2012-12-02T21:30:39.613 回答