I'd like to get the integer value from my string. Below is my example.
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
But I just want to get the score which is 10. How can I do this?
UPDATED:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
bfLog.createEntry( firstNumber );
I save this to sqlite database.
You can use one of the String
regex replace
methods to capture the first digits in a captured group :
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
.*?
consumes initial non-digits(non-greedy) (\\\\d+)
Get the one or more available digits in a group! .*
Everything else ( greedy ). This depends on whether anything else can change in your string.
If it's always the same apart from the number, you can use
int score = Integer.parseInt(strScore.substring(14,16))
because the digits "10" are at index 14 and 15 of the string. If other stuff changes in your string, you should use a regular expression :
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
You can try this:
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
String intIndex = strScore.valueOf(10);
String intIndex = 10 // Result
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.