Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get int from String, also containing letters, in Java

Tags:

java

integer

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() fails since the string must be entirely a number.

like image 514
DisgruntledGoat Avatar asked Feb 26 '10 00:02

DisgruntledGoat


People also ask

How do you check if a string contains both alphabets and numbers in Java?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

Can int contain letters?

Yes, that's fine. Characters are simply small integers, so of course the smaller value fits in the larger int variable, there's nothing to warn about. Many standard C functions use int to transport single characters, since they then also get the possibility to express EOF (which is not a character).

How do you check if a string contains a letter in Java?

In order to check if a String has only Unicode letters in Java, we use the isDigit() and charAt() methods with decision-making statements. The isLetter(int codePoint) method determines whether the specific character (Unicode codePoint) is a letter. It returns a boolean value, either true or false.


2 Answers

Replace all non-digit with blank: the remaining string contains only digits.

Integer.parseInt(s.replaceAll("[\\D]", ""))

This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.

If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:

s.matches("[\\d]+[A-Za-z]?")
like image 112
polygenelubricants Avatar answered Sep 23 '22 15:09

polygenelubricants


The NumberFormat class will only parse the string until it reaches a non-parseable character:

((Number)NumberFormat.getInstance().parse("123e")).intValue()

will hence return 123.

like image 20
jarnbjo Avatar answered Sep 21 '22 15:09

jarnbjo