I only found a way to do it the opposite way round: create a comma separated string from an int list or array, but not on how to convert input like string str = "1,2,3,4,5";
to an array or list of ints.
Here is my implementation (inspired by this post by Eric Lippert):
public static IEnumerable<int> StringToIntList(string str) { if (String.IsNullOrEmpty(str)) { yield break; } var chunks = str.Split(',').AsEnumerable(); using (var rator = chunks.GetEnumerator()) { while (rator.MoveNext()) { int i = 0; if (Int32.TryParse(rator.Current, out i)) { yield return i; } else { continue; } } } }
Do you think this is a good approach or is there a more easy, maybe even built in way?
EDIT: Sorry for any confusion, but the method needs to handle invalid input like "1,2,,,3"
or "###, 5,"
etc. by skipping it.
Given a string of comma separated numbers, we want to convert that string to a Python list of integers The idea here is to split the string into tokens then convert each token to an integer. We can do that in a couple of ways. Let us see how… Same as before but using map…
Convert a String to Integer Array in C/C++. Given a string str containing numbers separated with “, “. The task is to convert it into an integer array and find the sum of that array. Examples: Approach: Create an empty array with size as string length and initialize all of the elements of array to zero. Start traversing the string.
The string.split () method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer.parseInt () method and store that value integer value to the Integer array. How to add an element to an Array in Java?
Create an empty array with size as string length and initialize all of the elements of array to zero. Start traversing the string. Check if the character at the current index in the string is a comma (,).
You should use a foreach loop, like this:
public static IEnumerable<int> StringToIntList(string str) { if (String.IsNullOrEmpty(str)) yield break; foreach(var s in str.Split(',')) { int num; if (int.TryParse(s, out num)) yield return num; } }
Note that like your original post, this will ignore numbers that couldn't be parsed.
If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:
return (str ?? "").Split(',').Select<string, int>(int.Parse);
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