問(wèn)題描述
如何從 423e
等字符串中獲取 int 值 - 即包含數(shù)字但也可能包含字母的字符串?
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()
失敗,因?yàn)樽址仨毻耆菙?shù)字.
Integer.parseInt()
fails since the string must be entirely a number.
推薦答案
除非你說(shuō)的是 base 16 數(shù)字(有一種方法可以解析為 Hex),否則你需要明確地分離出你感興趣的部分,然后轉(zhuǎn)換它.畢竟,以 10 為底的 23e44e11d 之類的語(yǔ)義是什么?
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?
如果你確定你只有一個(gè)數(shù)字,正則表達(dá)式就可以解決問(wèn)題.Java 有一個(gè)內(nèi)置的正則表達(dá)式解析器.
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.
另一方面,如果您的目標(biāo)是連接所有數(shù)字并轉(zhuǎn)儲(chǔ) alpha,那么通過(guò)逐個(gè)字符迭代以使用 StringBuilder 構(gòu)建一個(gè)字符串,然后解析該字符串,這是相當(dāng)簡(jiǎn)單的.
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.
這篇關(guān)于在Java中從String中獲取int,也包含字母的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!