Easiest Way to Parse a Comma Delimited String to Some Kind of Object I Can Loop Through to Access the Individual Values

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

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.

Parsing a string of comma separated values

string input = "22,10 ,8 , 13";
var output = input.Split(',').Select(i=>i.Trim());

Retrieving and using values from a comma seperated string

You could try this one:

// Split the comma separated list to an array that will contain the words you want.
string[] words = commaSeparatedList.Split(',');

// Iterate through the words in array called words
foreach(string word in words)
{
// Code for insert the word in your database.
}

However, I have to point out here that the above approach is not optimal. The reason why I say this is the fact that for each word you have in the words you would have to make a round trip to the database to insert it into the corresponding table of your database. That being said I would suggest you create a stored procedure, in which you will pass this string, and then in your database you would try to get the words from the comma separated list and insert them in the corresponding table. The latter would be only one round trip to the database.

Get a specific value from comma separated string

You can use string Split method

string data = "0,0,0.1987,22.13";
string value = data.Split(',')[3];

How to split a comma separated string and process in a loop using JavaScript

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
}

Edit:

After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split will also take a regular expression as an argument:

'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]

This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.

And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map or forEach methods, then you could just simply do the following:

myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
console.log(myString);
});

How to get second values from a string (comma-separated value) in C#

Use Split(char)

string x = "12,1108,06";
var result = x.Split(',').Skip(1).FirstOrDefault();

or

string x = "12,1108,06";
var result = x.Split(',')[1];

Javascript: How to loop through data object and create a comma separated file

You need to append all of the items, comma separated, to a string in each loop iteration and push it to your textarray variable.

After the loop, join the textarray with newline escape sequence (\n)

var textarray = [];

var getRandValue = () => {
var fakeValues = ['Lorem', 'Ipsum', 'Dolar', 'Sit', 'Amet', 'Bla', 'bla']
return fakeValues[Math.floor(Math.random() * fakeValues.length)]
}

for(var i = 0; i < 10; i++){ //data is my object
var sms = getRandValue()
var date = getRandValue()
var code = getRandValue()
var type = getRandValue()
var mixer = getRandValue()
var quality = getRandValue()
var csvLine = `${sms}, ${date}, ${code}, ${type}, ${mixer}, ${quality}`
textarray.push(csvLine)
}

var resultCSV = textarray.join('\n')

var output = document.getElementById('output')

output.innerText = resultCSV
<div id="output"></div>

Loop through a comma-separated shell variable

You can use the following script to dynamically traverse through your variable, no matter how many fields it has as long as it is only comma separated.

variable=abc,def,ghij
for i in $(echo $variable | sed "s/,/ /g")
do
# call your procedure/other scripts here below
echo "$i"
done

Instead of the echo "$i" call above, between the do and done inside the for loop, you can invoke your procedure proc "$i".


Update: The above snippet works if the value of variable does not contain spaces. If you have such a requirement, please use one of the solutions that can change IFS and then parse your variable.



Related Topics



Leave a reply



Submit