Converting a String with spaces to an Integer in java

前端 未结 5 1777
温柔的废话
温柔的废话 2021-02-19 21:59

I\'m trying to convert a String variable into an integer, only the String looks like this (for example):

String string = \" 12\";

And so the St

5条回答
  •  情歌与酒
    2021-02-19 22:46

    The string split() method works well if you have a string of multiple numbers separated by spaces.

    String numbers = "1 23 456";
    String[] numbersArray = numbers.split(" "); // splitting string by spaces
    System.out.println(numbersArray.toString());
    // output ["1","23","456"]
    

    Then you can use Integer.parseInt() on each index of the array. Hope that helps

提交回复
热议问题