Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma separated string of ints to int array

Tags:

c#

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.

like image 295
Max Avatar asked Nov 19 '09 14:11

Max


People also ask

How to convert a string of comma separated numbers to integers?

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…

How to convert string to integer array in C/C++?

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.

How to convert a string to an integer in Java?

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?

How do I get a comma from a string in Python?

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 (,).


1 Answers

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); 
like image 110
SLaks Avatar answered Sep 21 '22 14:09

SLaks