如何计算字符串中所有数字的总和 [英] How to calculate sum of all numbers in a string

查看:70
本文介绍了如何计算字符串中所有数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算字符串中所有数字的总和?在下面的示例中,预期结果将为 4 + 8 + 9 + 6 + 3 + 5 .我的尝试在下面.我还可以只计算那些可以被2整除的数字的总和吗?

How do I calculate the sum of all the numbers in a string? In the example below, the expected result would be 4+8+9+6+3+5. My attempt is below. Also could I calculate the sum of only those numbers which are divisible by 2?

int sum=0;
String s = "jklmn489pjro635ops";
for(int i=0; i<s.length(); i++) {
    char temp = s.charAt(i);
    if (Character.isDigit(temp)) {
        int b = Integer.parseInt(String.valueOf(temp));
        sum=sum+b;
    }
}
System.out.println(sum);

推荐答案

将字符解析为 String ,然后解析为 Integer 太昂贵了,因为您已经有一个char.您应该尝试这样做:

Parsing chars back to String and then to Integer is too expensive, since you already have a char. You should try doing this:

 String a = "jklmn489pjro635ops";
 int sum = 0;
 int evenSum = 0;
 for (char c : a.replaceAll("\\D", "").toCharArray()) {
     int digit = c - '0';
     sum += digit;
     if (digit % 2 == 0) {
         evenSum += digit;
     }
 }
 System.out.println(sum);
 System.out.println(evenSum);

这篇关于如何计算字符串中所有数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆