How To Sum digits in a String in Java

In this post, we will learn How to separate out digits from a String and How to sum those digits.

Algorithm:

  1. Take a String.
  2. Convert it into array of characters
  3. Apply for loop till length of char array
  4. Using isDigit() method we can check the digits in string.
  5. If isDigit() will return true then print that index value.
  6. That digit is in char form. We will convert it into String then Integer.
  7. Using sum variable, we will sum it.

 

Code: Sum of Digits of a number in String

package demopkg;

public class FilterSpecialChar {

    public static void main(String[] args) {

        String str1 = "dhj34dfhf9fs";

        
        char[] c = str1.toCharArray();

        int sum = 0;

        for (int i = 0; i < c.length; i++) {

            if (Character.isDigit(c[i])) {

                System.out.print("Digits in the String : " + c[i]);
                System.out.println();

                int a = Integer.parseInt(String.valueOf(c[i]));

                sum = sum + a;

            }

        }
        System.out.println("Sum of Digits is : " + sum);

    }

}

Output:


How to Find Sum of Digits of a Number in Java:

Algorithm:

  1. Take a number into int data type.
  2. Take two more variable for reminder and sum.
  3. Check number is greater than 0 or not using while loop.
  4. Calculate reminder and sum it and store it into sum variable.
  5. For skip last digit in each iteration we will divide it by 10.

Code: Sum of Digits of a Number in Java

package demopkg;

public class SumDigitsInnumber {
    
    public static void main(String[] args) {
        
        int number = 2345;
        
        int r, sum=0;
        
        while(number>0) {
            
            r = number%10;
            sum = sum + r;
            number = number/10;
                        
        }
        
        System.out.println("Sum of digits :" + sum);
        
        
        
    }

}

Output:

Sum of digits in a Number

 

I hope this tutorial was helpful for you. Happy Learning 🙂

 

Must Read: How To reverse a String in Java

 

Leave a Comment