Converting a String with spaces to an Integer in java

前端 未结 5 1704
温柔的废话
温柔的废话 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:36

    Use the string trim function in Java to first get a string without the spaces, then parse it...

    1.) Remove spaces with trim ... String#trim

    String stringWithoutSpace = string.trim();
    

    2.) Parse the string without spaces ... Integer#parseInt

    int integer = Integer.parseInt(stringWithoutSpace);
    

    3.) Do everything above in one step ...

    int integer = Integer.parseInt(string.trim());
    

提交回复
热议问题