给定一行带数字的字符串,找出里边的数字,并相加,相邻的数字是一个整体。

给定一行带数字的字符串,找出里边的数字,并相加,相邻的是一个整体。如“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);
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值