12

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.

1
  • Do you need to use these variables outside of the foreach scope? Commented Sep 11, 2011 at 12:03

3 Answers 3

15

Get rid of the ForEach in this case.

It's just:

string x = dates[0];
string y = dates[1];
Sign up to request clarification or add additional context in comments.

5 Comments

To avoid runtime error: string y = dates.Length > 1 ? dates[1] : "";
@Shadow Wizard: If the data in line is incorrect a runtime error is probably better then assigning some random value.
@Peter empty string is not random and common default value. "Index was outside the bounds of the array" won't mean much to the end user.
@Shadow Wizard: I am not saying the end user should see the exception. "Index was outside the bounds of the array" will mean a lot to a programmer reading a log file that came from a system that failed in production. With your choice of default value you are already hiding an error, it could be the empty string was already in the data: "2011-09-11," or was generated by the inline if. Whether or not you present the user with some message entirely depends on whether this is user interface code or not.
@Peter well, I count on the OP here to use the information wisely.. I just gave warning that many times is overlooked and causing unexpected crash when simple default value solve the whole thing.
9

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);

1 Comment

I am surprised that there is no like python way, like var a, b , d = line.Split(",")
4

Do you mean like this?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.