将字符串中的数字求和,然后将数字替换为总和

时间:2019-05-31 23:04:34

标签: java

我是Java的初学者,并尝试编写代码以字符串中的数字总和替换数字。

对于Ex:对于输入abc123def023,输出为abc6def5

我能够编写代码以对所有数字求和,但是无法像上面的示例那样找出如何求和和替换。

2 个答案:

答案 0 :(得分:0)

这是一个非常简单的实现:

public static String sumConsecutiveNumbers(String text)
{
    final char[] chars = text.toCharArray();
    final StringBuilder sResult = new StringBuilder();
    int iResult = 0;
    /*
     * Iterate over each character
     */
    for (char aChar : chars)
    {
        /*
         * If the character is a digit convert it
         * to an (non-ascii) integer value and add to sum
         */
        if (Character.isDigit(aChar)) {
            iResult += Integer.valueOf(Character.toString(aChar));
        }
        else {
            /* Current character is not a digit but a last one was
             * so append the sum result to string and reset the value
             */
            if (iResult != 0) {
                sResult.append(iResult);
                iResult = 0;
            }
            /* Appending non-digit character here
             */
            sResult.append(aChar);
        }
    }
    /* Check for special case scenario where the last
     * character was a digit which mean it did not get
     * a chance to be proccessed in the loop
     */
    if (iResult != 0)
        sResult.append(iResult);

    return sResult.toString();
}

public static void main(String[] args)
{
    String text = "abc123def023egh723ijk194";
    String result = sumConsecutiveNumbers(text);

    System.out.println("Original string: " + text);
    System.out.println("Processed string: " + result);
}

如果您对更高级的(但性能更高一点)方法感兴趣,那么这里的regex解决方案同样适用。就个人而言,这可能是我的处理方式:

public static String sumConsecutiveNumbersWithRegex(String text)
{
    Matcher matcher = Pattern.compile("\\d+").matcher(text);
    /*
     * Store groups in a set so we dont get duplicates
     */
    java.util.Set<String> groups = new java.util.HashSet<>();

    while (matcher.find())
    {
        String group = matcher.group();
        if (!groups.contains(group))
        {
            /* Calculate the sum of number group and replace
             * all occurances of that group with the calculated sum
             */
            int sum = group.chars().map(Character::getNumericValue).sum();
            text = text.replace(group, String.valueOf(sum));
            groups.add(group);
        }
    }
    return text;
}

输出

Original string: abc123def023egh723ijk194
Processed string: abc6def5egh12ijk14

答案 1 :(得分:-2)

您将要遍历字符串。当您找到不是数字的字符时:Character.isDigit(string.charAt(index)),可以累加数字,直到再次遇到字母!Character.isDigit(string.charAt(index))为止。