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,也包含字母
基础教程推荐
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01