Get int from String, also containing letters, in Java

前端 未结 6 791
臣服心动
臣服心动 2020-11-28 10:05

How can I get the int value from a string such as 423e - i.e. a string that contains a number but also maybe a letter?

Integer.parseInt() f

6条回答
  •  难免孤独
    2020-11-28 10:25

    Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().

    Something like:

        String something = "423e";
        int length = something.length();
        String result = "";
        for (int i = 0; i < length; i++) {
            Character character = something.charAt(i);
            if (Character.isDigit(character)) {
                result += character;
            }
        }
        System.out.println("result is: " + result);
    

提交回复
热议问题