Monday, March 25, 2013

[C#] Split That Newline

Sample text string:


I got a text box that receives multi-liner string. I want to get the data each line so I need to split it. I got some cases regarding this.

First case:
String[] myArray = textBoxInput.Split('\n');

Yes, it may separate them correctly but if you look closely a '\r' will be added at the end of each string so the myArray will now be {"1=2\r"},{"3=4\r"},{"5=6"}.

The newline is compose of "\r\n" instead of just the common '\n'. Since you split it using '\n', then the '\r' was left behind.

Second case:
String[] myArray = textBoxInput.Split('\r\n');

This case would give some sort of error. That may lead you to the third case.

Third case:
String[] myArray = textBoxInput.Split("\r\n");

Notice that I just change the single quotes into double quotes yet still it will give you an error.

You might be frustrated or annoyed right now. What the heck am I gonna do?!

Here's the solution I got for you:
String[] myArray = Regex.Split(textBoxInput, "\r\n");


String[] myArray = Regex.Split(textBoxInput, Environment.NewLine);

It may or may not be the best solution but that's what I got for now. Enjoy!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...