用'\ r \ n'分割文字 [英] Split text with '\r\n'

查看:64
本文介绍了用'\ r \ n'分割文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注文章

然后我想到了以下代码:

And I came up with this code:

string FileName = "C:\\test.txt";

using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
    string[] stringSeparators = new string[] { "\r\n" };
    string text = sr.ReadToEnd();
    string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
    foreach (string s in lines)
    {
        Console.WriteLine(s);
    }
}

以下是示例文本:

somet interesting text\n
some text that should be in the same line\r\n
some text should be in another line

以下是输出:

somet interesting text\r\n
some text that should be in the same line\r\n
some text should be in another line\r\n

但是我想要的是这个

somet interesting textsome text that should be in the same line\r\n
some text should be in another line\r\n

我想我应该得到这个结果,但是不知何故我缺少了一些东西...

I think I should get this result but somehow I am missing something...

推荐答案

问题不在于分割,而在于 WriteLine .用 WriteLine 打印的字符串中的 \ n 将产生多余"行.

The problem is not with the splitting but rather with the WriteLine. A \n in a string printed with WriteLine will produce an "extra" line.

示例

var text = 
  "somet interesting text\n" +
  "some text that should be in the same line\r\n" +
  "some text should be in another line";

string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
   Console.WriteLine(s); //But will print 3 lines in total.
}

要解决此问题,请在打印字符串之前先删除 \ n .

To fix the problem remove \n before you print the string.

Console.WriteLine(s.Replace("\n", ""));

这篇关于用'\ r \ n'分割文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆