Write a program to return the sum of the digits present in the given string


  • The class Sum_Digits_String contains a method sum_digits that takes a string as input and returns an integer.
  • The method sum_digits iterates through each character in the input string using a for loop.
  • For each character, it checks if it is a digit using the Character.isDigit method. If it is a digit, it extracts the digit as a string and converts it to an integer using the Integer.parseInt method.
  • The integer value of each digit is added to a running sum variable.
  • At the end of the loop, the method returns the final sum.

Source Code

public class Sum_Digits_String
{
	public int sum_digits(String str) 
	{
		int l = str.length();
		int sum = 0;
		for (int i = 0; i < l; i++) 
		{
			if (Character.isDigit(str.charAt(i))) 
			{
				String tmp = str.substring(i,i+1);
				sum += Integer.parseInt(tmp);
			}
		}
		return sum;
	}
	public static void main (String[] args)
	{
		Sum_Digits_String m = new Sum_Digits_String();
		String str =  "a1b23c3d4e5hf";
		System.out.println("Given String : "+str);
		System.out.println("Sum of Digits in String : "+m.sum_digits(str));
	}
}

Output

Given String : a1b23c3d4e5hf
Sum of Digits in String : 18

Example Programs