Get int from String, also containing letters, in Java

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

提交回复
热议问题