给定一行带数字的字符串,找出里边的数字,并相加,相邻的是一个整体。如“asd10asd10fd10fd10” 10+10+10+10 = 40;得到结果为40。
代码如下:
先定义一个递归方法,来截取字符串并查找数字:
public static void getNum(String s, int[] is, int count) { //s为查找的字符串,is为存储字符串中数字的数组,count为当前数组索引
char[] c = s.toCharArray();
a: for (int i = 0; i < c.length; i++) {
if (c[i] >= 48 && c[i] <= 58) { //如果i处索引字符为数字
for (int j = i + 1; j < c.length; j++) { //查找i索引往后的字符
if (c[j] < 48 || c[j] > 58) { //当找到的字符不为数字时
String s1 = s.substring(i, j); //截取查询到的数字字符串部分
is[count] = Integer.parseInt(s1); //将该数字字符串转为int
count++; //索引+1
String s2 = s.substring(j); //从字符不为数字的索引位置截取原有字符串
getNum(s2, is, count); //传参递归
break a;
} else if (j == c.length - 1) { //当i索引往后的字符都是数字字符时
String s3 = s.substring(i);
is[count] = Integer.parseInt(s3);
count++;
break a;
}
}
}
}
}
设计main方法调用递归:
public static void main(String[] args) {
String s = "asd10asd10fd10fd10";
int[] is = new int[s.toCharArray().length]; //定义int数组存储字符串中数字
int count = 0; //定义count为int数组索引值
getNum(s, is, count); //调用递归
int sum = 0;
for (int i : is) {
sum += i;
}
System.out.println(sum);
}