C # Split a string into separate variables

I am trying to split a string into separate string variables when a comma is found.

string[] dates = line.Split(','); foreach (string comma in dates) { string x = // String on the left of the comma string y = // String on the right of the comma } 

I need to create a string variable for a string on each side of the comma. Thanks.

+7
source share
3 answers

Get rid of ForEach in this case.

It's simple:

 string x = dates[0]; string y = dates[1]; 
+9
source

Just get the lines from the array:

 string[] dates = line.Split(','); string x = dates[0]; string y = dates[1]; 

If there can be more than one comma, you must indicate that you want only two lines:

 string[] dates = line.Split(new char[]{','}, 2); 

Another option is to use string operations:

 int index = lines.IndexOf(','); string x = lines.Substring(0, index); string y = lines.Substring(index + 1); 
+5
source

Do you mean this?

  string x = dates[0]; string y = dates[1]; 
+4
source

All Articles