4

If the String is something like "19 35 91 12 36 48 59" and I want an array of the same structure.

I already tried

array[]=Integer.parseInt(str);
flavio.donze
  • 7,432
  • 9
  • 58
  • 91
Alex_70
  • 71
  • 1
  • 1
  • 2
  • 2
    There is no single method in Java API for that. Spit string on space, check how many elements you got, create int array, iterate over tokens, parse them and place in int array. – Pshemo Dec 09 '18 at 17:28
  • 1
    Where are you stuck? What have you tried? – Nicholas K Dec 09 '18 at 17:28
  • 1
    This seems like something that has probably already been answered. You should try searching for other questions with answers that solve your problem before you post. – LuminousNutria Dec 09 '18 at 17:32
  • Does this answer your question? [Converting a String Array to an Int array](https://stackoverflow.com/questions/21677530/converting-a-string-array-to-an-int-array) – Mr. Jain Aug 08 '20 at 17:18

4 Answers4

7

I'd split the string, stream the array, parse each element separately and collect them to an array:

int[] result = Arrays.stream(str.split(" ")).mapToInt(Integer::parseInt).toArray();
Mureinik
  • 297,002
  • 52
  • 306
  • 350
4

if they are separated by spaces you can convert them one by one like this

String array = "19 35 91 12 36 48 59";
// separate them by space
String[] splited = array.split(" ");
// here we will save the numbers
int[] numbers = new int[splited.length];
for(int i = 0; i < splited.length; i++) {
    numbers[i] = Integer.parseInt(splited[i]);
}
System.out.println(Arrays.toString(numbers));        
elbraulio
  • 994
  • 6
  • 15
1

You might could do something like this as well, even though it is maybe not as pretty as the solution above:

 String S;
 int Array[]= new int[S.length()];
 int Counter=0;
 for(int i=0; i<S.length(); i++){
     if(Character.isDigit(S.charAt(i))==true){
        Array[Counter]=Integer.parseInt(S.charAt(i)+"");
        Counter++;
     }
 }

Downside to is, that you will have an array that is partly empty, if the String is not entirely consisting out of digits. Depending on what you use the array for, you might want to use something else.

wittn
  • 298
  • 5
  • 16
  • Oh I misread the question I think, since you want the same structure in the array, which means including the spaces I would recommend following: String S; char array[]=S.toCharArray(); – wittn Dec 09 '18 at 17:57
1

If you want an Integer[] array instead of int[] use:

String input = "19 35 91 12 36 48 59";
String[] array = input.split(" ");
Integer[] result = Stream.of(array).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
flavio.donze
  • 7,432
  • 9
  • 58
  • 91