Get int from String, also containing letters, in Java

前端 未结 6 775
臣服心动
臣服心动 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:19

    You can also use Scanner :

    Scanner s = new Scanner(MyString);
    s.nextInt();
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-28 10:32

    Just go through the string, building up an int as usual, but ignore non-number characters:

    int res = 0;
    for (int i=0; i < str.length(); i++) {
        char c = s.charAt(i);
        if (c < '0' || c > '9') continue;
        res = res * 10 + (c - '0');
    }
    
    0 讨论(0)
  • 2020-11-28 10:33

    The NumberFormat class will only parse the string until it reaches a non-parseable character:

    ((Number)NumberFormat.getInstance().parse("123e")).intValue()
    

    will hence return 123.

    0 讨论(0)
  • 2020-11-28 10:34

    Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?

    Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.

    If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.

    0 讨论(0)
  • 2020-11-28 10:35

    Replace all non-digit with blank: the remaining string contains only digits.

    Integer.parseInt(s.replaceAll("[\\D]", ""))
    

    This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.

    If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:

    s.matches("[\\d]+[A-Za-z]?")
    
    0 讨论(0)
提交回复
热议问题