在Java中从String中获取int,也包含字母

2022-01-14 00:00:00 integer java

如何从 423e 等字符串中获取 int 值 - 即包含数字但也可能包含字母的字符串?

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() 失败,因为字符串必须完全是数字.

Integer.parseInt() fails since the string must be entirely a number.

推荐答案

除非你说的是 base 16 数字(有一种方法可以解析为 Hex),否则你需要明确地分离出你感兴趣的部分,然后转换它.毕竟,以 10 为底的 23e44e11d 之类的语义是什么?

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?

如果你确定你只有一个数字,正则表达式就可以解决问题.Java 有一个内置的正则表达式解析器.

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.

另一方面,如果您的目标是连接所有数字并转储 alpha,那么通过逐个字符迭代以使用 StringBuilder 构建一个字符串,然后解析该字符串,这是相当简单的.

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.

相关文章