输入新行时字数不起作用

时间:2015-06-11 20:49:53

标签: c# split newline

关于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;

2 个答案:

答案 0 :(得分:0)

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++;
}

答案 1 :(得分:0)

我自己有点像初学者,对不起,如果这不是一个好的答案,但我刚刚在c#中完成了一堆文本内容,我可能会通过替换将出现的换行符来实现在原始字符串中用“\ n”或“\ r”作为空格,“” - 类似于:

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