In this post, we will learn How to separate out digits from a String and How to sum those digits.
Table of Contents
Algorithm:
- Take a String.
- Convert it into array of characters
- Apply for loop till length of char array
- Using isDigit() method we can check the digits in string.
- If isDigit() will return true then print that index value.
- That digit is in char form. We will convert it into String then Integer.
- 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:
- Take a number into int data type.
- Take two more variable for reminder and sum.
- Check number is greater than 0 or not using while loop.
- Calculate reminder and sum it and store it into sum variable.
- 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:
I hope this tutorial was helpful for you. Happy Learning 🙂
Must Read: How To reverse a String in Java