7

I have string s = "158,141,90,86";

How I can convert them into int[]?

3
  • 1
    DO you want 4 elements in the Int[] array? Commented Sep 11, 2010 at 10:48
  • 1
    @saurabh: As opposed to? Commented Sep 11, 2010 at 11:05
  • @Steve Townsend: Is this similar to ET.PhoneHome()? Commented Sep 11, 2010 at 21:43

4 Answers 4

28
int[] result = "158,141,90,86".Split(',').Select(int.Parse).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

17

Like this, with LINQ:

int[] array = s.Split(',')
               .Select(x => int.Parse(x))
               .ToArray();

Note that that will throw an exception if any element of the text isn't an integer. If you want to make it more resilient (if this is user-entered data for example) you'll need to use int.TryParse; at that point life becomes a bit more complicated in terms of the LINQ query.

EDIT: To make it parse to an int?[] (with a null value corresponding to each invalid substring) you could do something like:

int?[] array = s.Split(',')
                .Select(x => { 
                      int value;
                      return int.TryParse(x, out value) ? value : (int?)null;
                 })
                .ToArray();

As I said, it's not terribly nice :(

EDIT: In the comments, Dan commented on the "obsession" with the above approach instead of (presumably) a more imperative approach. In my view even the less-pleasant second version is still easier to read than the imperative alternative. The ugliness is only due to the ugly nature of int.TryParse, which is no less ugly when used in imperative code.

If int.TryParse either returned int? or Tuple<bool, int> then it would be as easy as the first version. Even converting from the tuple form to the nullable form would be simple, with one extra projection:

int[] array = s.Split(',')
               .Select(x => int.TryParseTuple(x))
               .Select(tuple => tuple.First ? tuple.Second : (int?) null)
               .ToArray();

8 Comments

For completeness how would it change if you had to try and parse the int?
@Chloe: To do that "right", you'd want to change it to an array of int?.
In his answer, Grif claims this produces an error. I admit I haven't tried it, but do you maybe need to replace with return int.TryParse(x, out value) ? (int?) value : null so that both branches of your conditional have the same type?
OK, I did just try it, and it looks like casting either branch of the conditional to int? will do.
Why the obsession with trying to do it all in one line, even at the expense of readability? (This is not just at Jon, but all the answers seem to fall into this).
|
1

An imperative solution would of course be:

        string[] sa = s.Split(',');
        int?[] array = new int?[sa.Length];
        int value;
        for (int i = 0; i < sa.Length; i++)
            if (int.TryParse(sa[i], out value))
                array[i] = value;
            else
                array[i] = null;

6 Comments

@Andrey: Ahh yes. Not much better than my code in this case, but might be very useful in other situations. Good to know it's possible. Thanks.
@Grif: It would have been helpful to have added a comment to my answer to let me know, rather than adding your own answer. I've fixed it.
@Jon Skeet: Somehow I don't seem to be able to do so. Or am I missing something? (Low Rep?)
@Grif: Yes, you need 50 rep to comment on other people's answers.
@Grif: Ah, that makes sense - sorry for the inappropriate suggestion. I forget about things like that :(
|
1

Another solution with LINQ/int?[] is:

return source.Split(',') 
                .Select(x => {  
                      int? value = null; 
                      int parsed;
                      if (int.TryParse(x, out parsed)) {
                          value = parsed;
                      }
                      return value; 
                 }) 
                .ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.