使用’\ r \ n’拆分文本

我正在关注这篇文章

我想出了这段代码:

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 

我想我应该得到这个结果,但不知怎的,我错过了一些东西……

问题不在于分裂,而在于WriteLine 。 用WriteLine打印的字符串中的\n将生成“额外”行。

 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

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

这对我有用。

 using System.IO; // string readStr = File.ReadAllText(file.FullName); string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries); 

我认为问题出在您的文本文件中。 它可能已经拆分成太多行,当你读它时,它会“添加”额外的\r和/或\n字符(因为它们存在于文件中)。 检查你的text变量是什么。

下面的代码(在带有文本的局部变量上)工作正常并分为2行:

 string[] stringSeparators = new string[] { "\r\n" }; string text = "somet interesting text\nsome text that should be in the same line\r\nsome text should be in another line"; string[] lines = text.Split(stringSeparators, StringSplitOptions.None); 

我采用了一种更紧凑的方法将文本区域的输入拆分为字符串列表。 如果符合您的目的,您可以使用它。

问题是你无法拆分\ r \ n所以我事先删除了\ n,只用\ r \ n拆分

 var serials = model.List.Replace("\n","").Split('\r').ToList(); 

我喜欢这种方法,因为你可以在一行中完成。

这对我有用。

 string stringSeparators = "\r\n"; string text = sr.ReadToEnd(); string lines = text.Replace(stringSeparators, ""); lines = lines.Replace("\\r\\n", "\r\n"); Console.WriteLine(lines); 

第一个替换替换文本文件的新行中的\r\n ,第二个替换文件读取时转换为\\r\\n的实际\r\n文本。 (当文件被读取时\成为\\ )。

使用静态File类更容易读取文件:

 // First read all the text into a single string. string text = File.ReadAllText(FileName); // Then split the lines at "\r\n". string[] stringSeparators = new string[] { "\r\n" }; string[] lines = text.Split(stringSeparators, StringSplitOptions.None); // Finally replace lonely '\r' and '\n' by whitespaces in each line. foreach (string s in lines) { Console.WriteLine(s.Replace('\r', ' ').Replace('\n', ' ')); } 

注意:文本可能还包含垂直制表符\v 。 这些由Microsoft Word用作手动换行符。

为了捕获任何可能的中断,您可以使用正则表达式进行替换

 Console.WriteLine(Regex.Replace(s, @"[\f\n\r\t\v]", " "));