Get int from String, also containing letters, in Java

前端 未结 6 797
臣服心动
臣服心动 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: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');
    }
    

提交回复
热议问题