Answer:
Algorithm:
- Take a int variable c=0.
- Run the loop from 0 to String length.
- Get the each index value using charAt() method which will return the char value.
- Convert that char into int by typecasting or any other way.
- Now check that ASCII fall into the range of 48-57 for 0-9 int number.
- If it matches then first convert that number into integer using Integer.parseInt().
- Then add with the c and store to the same variable i.e c.
- Repeat from 3-7 till the end of the loop.
- At the end of loop , Print c outside the loop.
Step-by-step explanation:
// Java program to calculate sum of all numbers present
// in a string containing alphanumeric characters
class GFG
{
// Function to calculate sum of all numbers present
// in a string containing alphanumeric characters
static int findSum(String str)
{
// A temporary string
String temp = "";
// holds sum of all numbers present in the string
int sum = 0;
// read each character in input string
for(int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
// if current character is a digit
if (Character.isDigit(ch))
temp += ch;
// if current character is an alphabet
else
{
// increment sum by number found earlier
// (if any)
sum += Integer.parseInt(temp);
// reset temporary string to empty
temp = "0";
}
}
// atoi(temp.c_str()) takes care of trailing
// numbers
return sum + Integer.parseInt(temp);
}
// Driver code
public static void main (String[] args)
{
// input alphanumeric string
String str = "1abc5yz7";
System.out.println(findSum(str));
}
}