3

I was wondering how I could convert numbers in a string value to an int[]. I have the following numbers stored in a string:

1,2,3,4

But I was wondering how I could get these numbers stored in an int[] so each value is stored into the int array.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
BytePhoenix
  • 47
  • 1
  • 6

5 Answers5

12

Try this:

string str = "1,2,3,4";
int[] array = str.Split(',').Select(x => int.Parse(x)).ToArray();

If there's a chance that you might have a string with double commas (ex: 1,,2,3,4) then this will work better as per @Callum Linington's comment:

int[] array = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
                 .Select(int.Parse)
                 .ToArray();

What the code above does it:

  1. Create an array of strings after the call to Split() so after that method call we'll have something like this: { "1", "2", "3", "4"}
  2. Then we pass each one these strings to int.Parse() which will convert them to 32-bit signed integers.
  3. We take all these integers and make an array out of them with ToArray().
Nasreddine
  • 36,610
  • 17
  • 75
  • 94
7

Use Linq:

string str = "1,2,3,4";
var result = str.Split(',').Select(c => Convert.ToInt32(c)).ToArray();

It could be even simpler by using method group:

var result = str.Split(',').Select(int.Parse).ToArray();

Also if you don't know more about Linq, there is another way with Array.ConvertAll method which converts an array of one type (array of strings after the call to Split()) to an array of another type(int[] as you want):

var result = Array.ConvertAll(str.Split(','), int.Parse);
Community
  • 1
  • 1
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
1
bool isInt = true;
string[] str = "1,2,3,4".Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
int counter = 0;
List<int> parsedInts = new List<int>(str.Length);

while(isInt && counter < str.Length)
{
    int parsedInt;
    isInt = int.TryParse(str[counter], out parsedInt);
    counter++;
    if (isInt) {
        parsedInts.Add(parsedInt);
    }
}

// then you can return the list as an array if you want
parsedInts.ToArray();

While this method is longer and more verbose, it actually makes sure you can parse the string to an int before assigning it to the array.

Be sure to note here that it will cancel out as soon as it cann't parse the string, however you are more than welcome to put in a else in the event you come across an erroneous data type.

Callum Linington
  • 14,213
  • 12
  • 75
  • 154
0

You can use,

string str = "1,2,3,4";
var arr = str.Split(',').Select(int.Parse).ToArray()
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0
Int32.Parse(stringname)

Or

Int32.TryParse(stringname,out outputvariable)

If it is comma separated then first split them stringname.split(',') which will return array of strings and parse them individually using a while loop.

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
encrypted name
  • 149
  • 3
  • 17