简体   繁体   中英

Split a string into a List<string>

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?

myData.Replace(",", String.Empty).Split(';').ToList();

Try this

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

Or:

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

Try This:

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

Use one more Split

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

So splittedArray[0][1] will be two

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM