
How can i calculate the sum for the given string variable "7 A B Z 6 2 ".The output should be 15.

The given code finds the digits from the given string that consists of letters also and calculate the sum of digits.
class CalculateSumFromString
{
public static void main(String[] args)
{
String st="7 A B Z 6 2 ";
String str=st.replace(" ","");
char ch[]=str.toCharArray();
int sum=0;
for(int i=0;i<ch.length;i++){
if(Character.isDigit(ch[i])){
String s = Character.toString(ch[i]);
int num = Integer.parseInt(s);
sum+=num;
}
}
System.out.println(sum);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.