简体   繁体   中英

how to read and extract an integer from a string in java

Given a string

7 + 45 * 65

How to check whether a given character of this string is an integer and then store the whole integer value in an integer variable?

Eg for 65, check if 6 is an integer, if yes, then store 65 in another integer variable. You can assume that the string can be converted into a character array.

Given that this looks like homework below are some tips for a simple way to parse and store each integer value.

  • Check out the API documentation for the Character class. This will contain methods for determining whether a character is a digit.
  • Consider using a StringBuilder to store the intermediate numerical result as you read in each digit of the number.
  • Check the Integer class API for methods to help with parsing the String value (stored within your StringBuilder ) and turning it into an int .
  • Finally, consider using a List (eg LinkedList) to store the int value.

Check out this post on exactly the same topic:

Java Programming - Evaluate String math expression

It looks like BeanShell has the cleanest method to do what you need. You could also try the JavaScript Engine method (although BeanShell looks much cleaner to me).

Easiest solution would be to use java.util.Scanner. You can set Scanner.useDelimeter("\\\\D+") which will mean skip any non-digit characters, and then call Scanner.nextInt() to get next Integer from the String.

If you want to work with characters, then use Character.isDigit(char c) .

为了获得快速而又肮脏的解决方案,我将使用StringTokenizer并尝试{Integer.parseInt()} catch(NumberFormatException){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM