What is the easiest way to parse a comma delimited string list of values into some kind of object that I can loop through, so that I can access the individual values easily?
example string: "0, 10, 20, 30, 100, 200"
I'm a bit new to C#, so forgive me for asking a simple question like this. Thanks.
Python split() method splits the string into a comma separated list. It separates string based on the separator delimiter. This method takes two parameters and both are optional.
(adj.) Comma-delimited is a type of data format in which each piece of data is separated by a comma. This is a popular format for transferring data from one application to another, because most database systems are able to import and export comma-delimited data.
The .NET String class simplifies the process of extracting the individual values between the commas. The Split method of the String class allows you to extract individual values separated by a specific character.
In the popping up Kutools for Excel dialog box, select the cells you want to split, and then click the OK button. 4. In the second popping up Kutools for Excel dialog box, select a cell for locating the splitting values, then click OK. Then you can see the comma separated values in selected cells are split into rows as bellow screenshot shown.
2. In the Split Cells dialog box, select Split to Rows or Split to Columns in the Type section as you need. And in the Specify a separator section, select the Other option, enter the comma symbol into the textbox, and then click the OK button. See screenshot:
In the first Convert Text to Columns Wizard dialog box, select the Delimited option, and then click the Next button. 3. In the second Convert Text to Columns Wizard dialog box, only check the Comma box in the Delimiters section, and click the Next button.
there are gotchas with this - but ultimately the simplest way will be to use
string s = [yourlongstring]; string[] values = s.Split(',');
If the number of commas and entries isn't important, and you want to get rid of 'empty' values then you can use
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
One thing, though - this will keep any whitespace before and after your strings. You could use a bit of Linq magic to solve that:
string[] values = s.Split(',').Select(sValue => sValue.Trim()).ToArray();
That's if you're using .Net 3.5 and you have the using System.Linq declaration at the top of your source file.
var stringToSplit = "0, 10, 20, 30, 100, 200";
// To parse your string var elements = test.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
// To Loop through foreach (string items in elements) { // enjoy }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With