PDA

Click to See Complete Forum and Search --> : simple -> how can I convert a multiline string to an array


MrPolite
Jun 11th, 2004, 06:12 PM
I have a string with a bunch of "new line" characters. I want each line to be an element of a string array. I dunno what I'm doing wrong but it doesnt work too well with String.Split

I'm doign this:
String.Split (Environment.NewLine.ToCharArray());

every other element of the array appears to be blank (""). what's the right way? :confused:

Pirate
Jun 11th, 2004, 10:37 PM
I did this and it looks it's working .....

System.IO.StreamReader sr=new System.IO.StreamReader("c:\\a.txt");
string[] ss =sr.ReadToEnd().Split(Environment.NewLine.ToCharArray());

foreach (string s in ss )
{
if (s !="")MessageBox.Show(s);
}
}

dj4uk
Jun 14th, 2004, 09:56 AM
Try:

string[] keywordArray = keywordString.Split('\n');

DJ

dj4uk
Jun 14th, 2004, 09:57 AM
Also you must remember that if there is more than one line return without any text they will still be split - which might be why some elements in the array are blank.

DJ

sunburnt
Jun 14th, 2004, 08:30 PM
Evironment.Newline is equal to "\r\n" (assuming windows here), so your splitting by each element in the char array {'\r', '\n'}. So when you get a file like this:

line 1 \r\n
line 2 \r\n

you end up with the following:
line 1 (ends at \r)
null string (between \r and \n)
line 2 (ends at \r)
null string (between \r and \n)

Does that make sense?