Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most simple way to convert comma separated string to int[]? [duplicate]

So I have comma-separated string like 1,5,7, so what's the most simple and native way to convert this string to int[]? I can write my own split function, but there's some interest how to do it in most native way. Thanks in advance guys!

like image 931
kseen Avatar asked Jul 05 '11 05:07

kseen


People also ask

How do I change a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.

How do you convert a string separated by a comma to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How can you convert information consisting of comma separated values into an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.


2 Answers

string s = "1,5,7"; int[] nums = Array.ConvertAll(s.Split(','), int.Parse); 

or, a LINQ-y version:

int[] nums = s.Split(',').Select(int.Parse).ToArray(); 

But the first one should be a teeny bit faster.

like image 144
Ben Voigt Avatar answered Oct 03 '22 04:10

Ben Voigt


string numbers = "1,5,7"; string[] pieces = numbers.Split(new string[] { "," },                                   StringSplitOptions.None);  int[] array2 = new int[pieces.length];  for(int i=0; i<pieces.length; i++)     array2[i] = Convert.ToInt32(pieces[i]); 
like image 20
MD Sayem Ahmed Avatar answered Oct 03 '22 05:10

MD Sayem Ahmed