从Java中获取int,也包含字母 [英] Get int from String, also containing letters, in Java

查看:165
本文介绍了从Java中获取int,也包含字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

除非你在谈论基数为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.

这篇关于从Java中获取int,也包含字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆