I need to split a string into newlines in .NET and the only way I know of to split strings is with the Split method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Well, actually split should do:
I did not know about Environment.Newline, but I guess this is a very good solution.
My try would have been:
The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.
EDIT:
As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.
To split on a string you need to use the overload that takes an array of strings:
Edit:
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:
What about using a
StringReader
?Just thought I would add my two-bits because the other solutions on this question do not fall into the reusable code classification and are not convenient. The following block of code extends the
string
object so that it is available as a natural method when working with strings.You can now use the
.Split()
function from any string as follows :To split on a newline char, simply pass
"\n"
or"\r\n"
as the delimiter parameter.Comment : It would be nice if Microsoft implemented this overload.
The RemoveEmptyStrings option will make sure you don't have empty entries due to \n following a \r
(Edit to reflect comments:) Note that it will also discard genuine empty lines in the text. This is usually what I want but it might not be your requirement.