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

Word count not working when entering new line

我一直在查看有关 C# 中字数统计的类似问题的其他堆栈溢出文章,但 none 在遇到问题时帮助了我。

我有一个文本框,可以从文本文件中输入文本。我按 enter 按钮在文本文件中创建一个新行,将文本分成三行。正文如下:

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

现在如您所见,应该有 17 个字,但我的字数只有 15 个。经过反复试验,我意识到问题一定出在换行上。每次换行时,它认为上一行的最后一个词和新行的第一个词一起作为一个词(或者这就是我认为程序正在思考的)。

我的问题是我下面的代码,我如何才能认识到如果有一个新行,它应该像 space 一样拆分单词?

下面是我的代码:

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:

The string that is returned does not contain the terminating carriage return or line feed.

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

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

考虑使用 StringBuilder class 重复连接字符串。

编辑:

要获得字符数,就像从未添加 space 一样,请执行:

int charCount = textLine.Length - lineCount;

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

int lineCount = 0;

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

我自己有点初学者,如果这不是一个很好的答案,我很抱歉,但我刚刚用 C# 完成了一堆文本内容,我可能会通过替换换行符来解决这个问题在原始字符串中显示为“\n”或“\r”,带有 space、“” - 类似于:

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