Program to find the digits from alphanumeric string and find the sum of digits.


This is program is about to find the digits from alpha numeric string and find the sum of all digits.
We will read the string character wise then it is possible to find the number from string. When we'll read each character we've to use the isDigit function of java which is defined in the Character class. isDigit function allows us to identify the given character is string or alphabet.

/******************************************************************************

Write a program to find the sum of digits found in given string.

*******************************************************************************/

public class Main
{
                public static void main(String[] args) {
                                int sum = 0;
                                String str = "sd54s4dfwer46df4d";
                                for(int i = 0; i < str.length(); i++){
                                                if(Character.isDigit(str.charAt(i))){
                                                                sum = sum + Integer.parseInt(String.valueOf(str.charAt(i)));
                                                                System.out.print(str.charAt(i)+" ");
                                                }
                                }
                                System.out.println("Sum of digits is : "+sum);
                }
}


Output:


If you have any question about it then please comment below.

0 Comments:

Post a Comment