3

I am trying to split a string into a List<string>. I have this string:

string myData = "one, two, three; four, five, six; seven, eight, nine";

And I would like the filled list of strings to look like:

one two three
four five six
seven eight nine

Meaning that I have to remove the commas(,) and the semi colons(;), so that for example the first row of the list, the second column will be two(without commas, semi colons or spaces).

I know that I can use .Split:

string[] splittedArray = myData.Split(';').ToArray();

This should produce a result like:

one, two, three,
four, five, six,
seven, eight, nine

How do I remove the commas(,) and put it in the list in that format?

1
  • 4
    You can use Replace() to replace the commas with nothing. Commented Jul 10, 2014 at 7:28

5 Answers 5

13
myData.Replace(",", String.Empty).Split(';').ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

Use String.Empty for the empty string. You know, just in case an empty string ever would look any different. ;-)
4

Try this

 string myData = "one, two, three; four, five, six; seven, eight, nine";
                string[] splittedArray = myData.Replace(",", "").Split(';').ToArray();
                List<string> list = splittedArray.ToList();

Comments

2
string[] splittedArray = myData.Split(';')
                        .Select(x => x.Replace(",","")
                        .ToArray();

Or:

string[] splittedArray = myData.Split(';')
                        .Select(x => string.Join(" ", x.Split(','))
                        .ToArray();

Comments

2

Use one more Split

var splittedArray = myData.Split(';').Select(s => s.Split(',').ToArray()).ToArray();

So splittedArray[0][1] will be two

Comments

2

Try This:

 string myData = "one, two, three; four, five, six; seven, eight, nine";
 List<string> list = myString.Replace(", ", " ").Split(';').ToList();

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.