Alex Alex - 1 month ago 9
Java Question

Split Numbers String to Integer Array

String contains an unknown length of numbers which are seperated by "-", for example:

string = "4-12-103-250-302"


I need these numbers in an integer array like this:

intArray[] = { 4, 12, 103, 250, 302 }


Can you give me a code example/solution?

Answer

You can use the String.Split method in Java.

Then convert the Array to an Integer Array.

string str = "4-12-103-250-302";
String[] parts = string.split("-");

int[] intArray = new int[parts.length];

for(int i = 0; i < parts.length -1; i++)
{
    intArray[i] = Integer.parseInt(parts[i]);
}

Then you can just access all of the parts just as an array would work.

intArray[0]
intArray[1]
.
.
etc
Comments