这是我的代码:
String addchar = "";
String tempchar;
int len = strline.length();
char[] chars = strline.toCharArray();
int amount = 0;
for (int i = 0; i < len; i++) {
tempchar = String.valueOf(chars[i]);
if (tempchar == "0" || tempchar == "1" || tempchar == "2" || tempchar == "3" || tempchar == "4" || tempchar == "5" || tempchar == "6" || tempchar == "7" || tempchar == "8" || tempchar == "9") {
addchar=tempchar+addchar;
}
}
amount=Integer.parseInt(addchar);
但是在运行此代码时,我发现amount
为空!
我想提取strline
答案 0 :(得分:1)
尝试使用Matcher
Matcher matcher = Pattern.compile("\\d+").matcher("a22dsdddd212");
while(matcher.find()) {
Log.e("number :-> ",matcher.group()+"");
}
答案 1 :(得分:1)
稍微不如Nilesh的答案优雅,但作为替代方案:
StringBuilder sb = new StringBuilder();
for (char c : strline.toCharArray()) {
if ((sb.length() == 0 && "-".equals(c)) || Character.isDigit(c)) sb.append(c);
}
int amount = Integer.parseInt(sb.toString());
修改修改后允许初始出现负号
答案 2 :(得分:0)
如果您想要所有数字字符,可以这样使用replaceALL:
String numericString = strline.replaceAll("[^0-9]", "");
然后使用ParseInt。
希望它有所帮助。