Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break a string in lines

I'm confused with what is the correct way to break lines.

I read somewhere that windows use \r\n to break lines, but this two codes produce the same

regex.split(sometext, "\r\n");
regex.split(sometext, "\n");

What it is the correct way?, these expressions always produce the same?

like image 923
mjsr Avatar asked Apr 07 '11 15:04

mjsr


People also ask

How do you split a string into lines?

Using String. NewLine , which gets the newline string defined for the current environment. Another way to split the string is using a Unicode character array. To split the string by line break, the character array should contain the CR and LF characters, i.e., carriage return \r and line feed \n .

How do you break a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


3 Answers

Use

var myArray = sometext.Split(Environment.NewLine);

Environment.NewLine will pick the correct one for your operating system. This will fail if the data was created on a different system. Something that might work on all systems, but have some unintended consequences is

var myArray = sometext.Split(new[] {'\r', '\n'}, 
    StringSplitOptions.RemoveEmptyEntries);

Some possible worrisome things is that it will remove all empty lines and split on carriage returns.

like image 135
Yuriy Faktorovich Avatar answered Oct 06 '22 23:10

Yuriy Faktorovich


If you want to support new-line characters for every platform (e.g. you need to parse input files, created under Linux/Windows/Mac in your ASP.NET web-site) and you do not carry about empty strings, I suggest to use this method instead:

myString.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)

This will return

["one","two","three"]

for input string

"one\r\ntwo\n\n\nthree"

Update: If you need to carry about empty lines, you can use

myString.Replace("\r\n", "\n").Split("\n")

This should work for both "\r\n" and "\n" EOL charracter files.

like image 36
Kluyg Avatar answered Oct 06 '22 23:10

Kluyg


You can use Environment.NewLine to make sure you get the correct one.

like image 2
Håvard Avatar answered Oct 06 '22 23:10

Håvard