输入新行时字数统计不起作用

本文关键字:统计 不起作用 新行时 输入 | 更新日期: 2023-09-27 17:55:21

我一直在查看其他堆栈溢出文章,这些文章涉及 C# 中的字数统计类似问题,但在我遇到的泡菜方面没有帮助我。

我有一个文本框,用于输入文本文件中的文本。文本被分成三行,我按 Enter 按钮在文本文件中创建新行。文中写道:

It's a test to see "if" the
application_for Top Image Systems
actually work. Hopefully it does work.

现在如您所见,应该有 17 个单词,但我的字数只说 15 个。经过一些试验和错误,我意识到问题一定是它在一个新的行中。每次它转到新行时,它都会认为前一行的最后一个单词和新行的第一个单词一起作为一个单词(或者这就是我认为程序正在思考的)。

我的问题是我在下面的代码中,我如何识别如果有新行,它应该像空格一样拆分单词?

下面是我的代码:

string nl = System.Environment.NewLine;
//Missing Code to read text file which I don't need to include in this example
do
{
    textLine = textLine + txtReader.ReadLine();
}
//Read line until there is no more characters
while (txtReader.Peek() != -1);
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words
int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;

输入新行时字数统计不起作用

txtReader.ReadLine();

掉你的换行符。从 msdn:

返回的字符串不包含终止回车符或换行符。

所以你必须手动添加它(或只添加一个空格)

textLine = textLine + txtReader.ReadLine() + " ";

请考虑使用 StringBuilder 类来重复连接字符串。

编辑:

要获得字符计数,就好像从未添加空格一样,请执行以下操作:

int charCount = textLine.Length - lineCount;

其中lineCount每次在 do-while 循环中添加空格时递增的整数:

int lineCount = 0;
do
{
    textLine = textLine + txtReader.ReadLine();
    lineCount++;
}

我自己有点初学者,对不起,如果这不是一个好的答案,但我刚刚用 c# 做了一堆文本内容,我可能会通过将原始字符串中显示为"'"或"''r"的换行符替换为空格" - 类似:

nl = nl.Replace("'r", " ");