Get int from String, also containing letters, in Java(在Java中从String中获取int,也包含字母)
问题描述
如何从 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.
这篇关于在Java中从String中获取int,也包含字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在Java中从String中获取int,也包含字母


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01