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?
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 .
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.
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.
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.
You can use Environment.NewLine
to make sure you get the correct one.
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