我被安排了一个创建 c# 控制台文本分析程序的任务。该程序允许用户逐字输入句子 单个句号是句子的结尾 双句号是打破循环并给出文本分析
我让程序正确计算单词和句子。
我的问题是:如何更改我的代码,使程序不会将句号计为一个字符?
以下是我到目前为止的代码
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.nnUse 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 来更正字符数,但它不起作用
提前感谢您的任何帮助。
在这里,您只是覆盖了CharCount
的值,丢弃了您之前所做的所有减法:
CharCount = newString.Length;
它可以更改为:
CharCount = CharCount + newString.Length;
为了给出正确的结果。
还有其他选项,例如计算句子中的.
数,在获得其长度之前将句子中的所有.
替换为空字符串等等。
关于样式的说明:在 C# 中,局部变量通常是 camelCase,而不是 PascalCase。
你可以只计算不是 "."
CharCount = newString.Where(c => !c.Equals('.') && !c.Equals(' ')).Count();
可以使用 LINQ 计算不是空格或点的字符。
int characterCount = s.Count(x => x != ' ' && x != '.');