I was following this article
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); } }
Here is the sample text:
somet interesting text\n some text that should be in the same line\r\n some text should be in another line
Here is the output:
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
But what I want is this:
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...
Description. newStr = splitlines( str ) splits str at newline characters and returns the result as the output array newStr . splitlines splits at actual newline characters, not at the literal \n . To split a string that contains \n , first use compose and then use splitlines .
To split a string on newlines, you can use the regular expression '\r?\ n|\r' which splits on all three '\r\n' , '\r' , and '\n' . A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence. You can also split a string on the system-dependent line separator string.
Use the str. splitlines() method to split a string by \r\n , e.g. my_list = my_str. splitlines() . The splitlines method splits the string on each newline character and returns a list of the lines in the string.
Use split() method to split by delimiter. If the argument is omitted, it will be split by whitespace, such as spaces, newlines \n , and tabs \t . Consecutive whitespace is processed together. A list of the words is returned.
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.
Example
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. }
To fix the problem remove \n
before you print the string.
Console.WriteLine(s.Replace("\n", ""));
This worked for me.
using System.IO; // string readStr = File.ReadAllText(file.FullName); string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With