求解一个计算字符串中出现的数字之和问题

兔兔土土 2019-05-17 01:30:30
...全文
115 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_43252604 2019-06-15
  • 打赏
  • 举报
回复
转换成字符数组,遍历
嗯嗯** 2019-05-20
  • 打赏
  • 举报
回复

class text {
	public static int count(String str) {
		char[] s = str.toCharArray();
		String number = "";
		int sum = 0;
		for(int i = 0; i < s.length; i++) {
			if(s[i] > 47 && s[i] < 58 ) {
				number =number + s[i];
				if(i != (s.length - 1)) {
					println(i);
					continue;
				}
			}
			if(number.length() > 0) {
				sum += Integer.valueOf(number);
				number="";
			}			
		}
		return sum;
	}
}




qq_40674493 2019-05-18
  • 打赏
  • 举报
回复

String str = "6ab11c333def521gh9i5jk61nm3n2";
StringBuffer buffer = new StringBuffer();
int sum = 0;
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {//使用Java类库的方法判断字符是否是数字
buffer.append(c);
} else if (buffer.length() > 0) {
sum += Integer.parseInt(buffer.toString());
buffer.delete(0, buffer.length());//清空缓存
}
}
if (buffer.length() > 0) {
sum += Integer.parseInt(buffer.toString());
}
System.out.println(sum);
nayi_224 2019-05-17
  • 打赏
  • 举报
回复
		String str = "1a2a3";
		
		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher matcher = pattern.matcher(str);
		
		int aa = 0;
		
		while(matcher.find()){
			aa += Integer.valueOf(matcher.group());
		}
		
		System.out.println(aa);
兔兔土土 2019-05-17
  • 打赏
  • 举报
回复
引用 4 楼 水边2 的回复:
正则是比较简单的作法,给你一个不用正则的:
int num = 0;
String lastNum = "";
String str = "1a2b3c44d";
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch >= '0' && ch <= '9') {
        lastNum += ch;
        continue;
    }
    if (lastNum.length() > 0) {
        num += Integer.valueOf(lastNum);
        lastNum = "";
    }
}
if (lastNum.length() > 0)
    num += Integer.valueOf(lastNum);
System.out.println(num);
牛逼老哥,多谢了!
兔兔土土 2019-05-17
  • 打赏
  • 举报
回复
这种如何得到里面的数字,有大神嘛
游北亮 2019-05-17
  • 打赏
  • 举报
回复
正则是比较简单的作法,给你一个不用正则的:
int num = 0;
String lastNum = "";
String str = "1a2b3c44d";
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (ch >= '0' && ch <= '9') {
        lastNum += ch;
        continue;
    }
    if (lastNum.length() > 0) {
        num += Integer.valueOf(lastNum);
        lastNum = "";
    }
}
if (lastNum.length() > 0)
    num += Integer.valueOf(lastNum);
System.out.println(num);
兔兔土土 2019-05-17
  • 打赏
  • 举报
回复
引用 2 楼 nayi_224 的回复:
		String str = "1a2a3";
		
		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher matcher = pattern.matcher(str);
		
		int aa = 0;
		
		while(matcher.find()){
			aa += Integer.valueOf(matcher.group());
		}
		
		System.out.println(aa);
多谢老哥,不过正则最近还没学到,最近学的IO流 您的解答我得好好研究研究,哈哈哈

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧