首页 文章

计算字符列表中的两位数

提问于
浏览
1

我正在写一个时髦的程序 . 我的输出如下

红色5green 5blue 10white 15

我想总结输出中的数字 . 总和将是35

我编写了以下逻辑但是程序返回17,这是正确的,因为下面的逻辑考虑了数字 .

你能指导我如何使程序理解两位数字吗?这样我得到了正确的金额?

for (int i =0; i < output.length(); i++)
    {
        {
            sum=sum+Character.getNumericValue(grps.charAt(i))
        }
    }

谢谢

4 回答

  • 0

    显然我不能在评论中编写代码,但只是继续回答你可以更进一步使用斜杠字符串,删除分号和System.out .

    String output = "red 5green 5blue 10white 15"
    int sum = 0
    
    for (String token : output.replaceAll(/\D+/, " ").trim().split(/\s+/)) {
        sum += Integer.parseInt(token)
    }
    
    println(sum)
    
  • 0

    既然您也为[groovy]标记了:

    您可以使用正则表达式 /\d+/ 在字符串中使用"findAll"数字字符串,将它们全部转换为数字,最后将它们转换为 sum() . 例如

    def sumNumberStrings(s) {
        s.findAll(/\d+/)*.toLong().sum()
    }
    assert 35==sumNumberStrings("red 5green 5blue 10white 15")
    
  • 0

    我会使用正则表达式替换所有带有空格的非数字, trim() 用于删除任何前导和尾随空格,然后分割(可选地连续)空格;喜欢,

    String output = "red 5green 5blue 10white 15";
    int sum = 0;
    for (String token : output.replaceAll("\\D+", " ").trim().split("\\s+")) {
        sum += Integer.parseInt(token);
    }
    System.out.println(sum);
    

    产出(按要求)

    35
    

    另一个选项是 Pattern 找到一个或多个数字的所有序列并将它们分组,然后使用循环解析并添加到 sum . 喜欢,

    Pattern p = Pattern.compile("(\\d+)");
    Matcher m = p.matcher(output);
    while (m.find()) {
        sum += Integer.parseInt(m.group(1));
    }
    System.out.println(sum);
    

    哪个也会给你 35 .

  • 2

    一个不需要使用正则表达式或其他复杂功能的简单算法将是这样的:

    String output = "red 5green 5blue 10white 15";
    
    // The result
    int sum = 0;
    // Sum of the current number
    int thisSum = 0;
    for (char c : output.toCharArray()) {
        // Iterate through characters
        if (Character.isDigit(c)) {
            // The current character is a digit so update thisSum so it includes the next digit.
            int digitValue = c - '0';
            thisSum = thisSum * 10 + digitValue;
        } else {
            // This character is not a digit, so add the last number and set thisSum 
            // to zero to prepare for the next number.
            sum += thisSum;
            thisSum = 0;
        }
    }
    // If the string ends with a number, ensure it is included in the sum.
    sum += thisSum;
    
    System.out.println(sum);
    

    这适用于任意数量的数字 .

相关问题