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!
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.
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.
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.
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.
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]);
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