問題描述
如何從 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,也包含字母的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!