scbushan05
7/7/2017 - 5:02 AM

Find the sum of the digits present in a String

Find the sum of the digits present in a String

/*
Input: 2ad12sdf4adf4asdf5asdf3sdf3sd20
Output: 53
*/
public class SumDigits {
	public static void main(String[] args) {
		System.out.println(sumDigits("2ad12sdf4adf4asdf5asdf3sdf3sd20"));
	}
	private static int sumDigits(String string) {
		String temp = "";
		int sum = 0;
		char[] c = string.toCharArray();
		for(int i = 0; i < c.length; i++){
			if(Character.isDigit(c[i])){
				temp = temp + c[i];
			}
			else{
				if(temp != ""){
					sum += Integer.parseInt(temp);
					temp = "";
				}
			}
		}
		if(temp!=""){
			sum += Integer.parseInt(temp); 
		}
		return sum;
	}
}