Thursday, July 27, 2017

Sum Numbers From A String


This simple but tricky programs is to filter numbers from a given string and find the sum of all those numbers.





public class StringFilter {

    public static void main(String[] args)
         {  
                 String s = "aB1cD2";
                 int sum=0;       
                 String s1=s.toLowerCase();
                 for(int i=0;i<s1.length();i++)
                 {
                          int m=Character.getNumericValue(s1.charAt(i));
                          if(m >=0  && m<=9)
                          {
                                sum += m;
                          }       
               
                  }
       
        System.out.println(s1+" :- "+sum);
    }

}



Output :  ab1cd2 :- 3

0 comments:

Post a Comment