Java string to int array

www.l‮uttua‬ri.com
Java string to int array

To convert a string of integers separated by a delimiter to an array of int values in Java, you can use the split method of the String class and the parseInt method of the Integer class.

Here's an example of how you can do this:

String s = "1,2,3,4,5";
String[] parts = s.split(",");
int[] array = new int[parts.length];
for (int i = 0; i < parts.length; i++) {
    array[i] = Integer.parseInt(parts[i]);
}

In this example, we're using the split method to split the input string at each occurrence of the "," delimiter, resulting in an array of strings. We then use a loop to iterate over each string and convert it to an int value using the parseInt method.

You can use a different delimiter by specifying a different string as the argument to the split method. For example, to split the string at each space character, you can use the following code:

String s = "1 2 3 4 5";
String[] parts = s.split(" ");
int[] array = new int[parts.length];
for (int i = 0; i < parts.length
Created Time:2017-10-17 20:18:53  Author:lautturi