[英]Java get integer value from string
我想从我的字符串中获取整数值。 以下是我的例子。
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
但我只想得到10分。我该怎么做?
更新:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
bfLog.createEntry( firstNumber );
我把它保存到sqlite数据库。
您可以使用String
regex replace
方法之一捕获捕获组中的第一个数字:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
.*?
消耗初始非数字(非贪婪) (\\\\d+)
获取组中的一个或多个可用数字! .*
其他一切( 贪婪 )。 这取决于你的字符串中是否还有其他变化。
如果它与数字总是相同的,你可以使用
int score = Integer.parseInt(strScore.substring(14,16))
因为数字“10”位于字符串的索引14和15处。 如果字符串中的其他内容发生更改,则应使用正则表达式:
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
你可以试试这个:
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
String intIndex = strScore.valueOf(10);
String intIndex = 10 // Result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.