Bali C
Bali C

Reputation: 31231

C# Split 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 be able to create a string variable for the string on each side of the comma. Thanks.

Upvotes: 12

Views: 44868

Answers (3)

Guffa
Guffa

Reputation: 700342

Just get the strings from the array:

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

If there could be more than one comma, you should specify that you only want two strings anyway:

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

Another alternative is to use string operations:

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

Upvotes: 9

user925777
user925777

Reputation:

Do you mean like this?

   string x = dates[0];
   string y = dates[1];

Upvotes: 4

LarsTech
LarsTech

Reputation: 81620

Get rid of the ForEach in this case.

It's just:

string x = dates[0];
string y = dates[1];

Upvotes: 15

Related Questions