4

I have the following code:

  string myTest = "Line1Test" + Environment.NewLine +
                  "Line2Test" + Environment.NewLine +
                  "Line3Test" + Environment.NewLine;
  string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray());

What I'm getting is data every other line in the new array. I think this is because the split line is splitting for both line feeds and carriage returns, but how can I just get one element per line?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
  • possible duplicate of [Easiest way to split a string on newlines in .net?](http://stackoverflow.com/questions/1547476/easiest-way-to-split-a-string-on-newlines-in-net) – Mark Byers Dec 14 '10 at 21:19

3 Answers3

24
string[] parseStr = myTest.Split(
    new string[] { Environment.NewLine },
    StringSplitOptions.None
);
Dinah
  • 52,922
  • 30
  • 133
  • 149
2

You may want to specify StringSplitOptions.RemoveEmptyEntries to, well, remove empty entries.

string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray(),
                                 StringSplitOptions.RemoveEmptyEntries);
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • Aside from that what you're doing isn't too logical, but it's probably a simplified example. – Kobi Dec 14 '10 at 21:16
  • 1
    Your code does work in this instance but I wouldn't recommend here. The OP may later need to modify the original code in a way that retains empty entries. If this came up, your code would no longer apply. – Dinah Dec 14 '10 at 21:22
  • @Dinah - True. This is an example on using `RemoveEmptyEntries`. Splitting on `Environment.NewLine` seems a little odd, I though it's worth mentioning it. – Kobi Dec 14 '10 at 21:25
  • -1: the problem is that OP was using the wrong overload. He was not splitting by CRLF, but by CR and LF. This proposed solution is only patchwork and may have adverse effects. It attempts to fix the consequences ignoring the causes. – ANeves Aug 10 '12 at 17:08
-1

One more way though may not be the best

string myTest = "Line1Test" + Environment.NewLine +
                  "Line2Test" + Environment.NewLine +
                  "Line3Test" + Environment.NewLine;          

string[] parseStr = myTest.Split(Environment.NewLine.ToCharArray()).Where(i => i != string.Empty).ToArray();
  • -1: does not identify the issue in the original question; also there is already an overload to skip empty entries. – ANeves Aug 10 '12 at 17:09