Calculate sum of all numbers present in a string - GeeksforGeeks
Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.
Read full article from Calculate sum of all numbers present in a string - GeeksforGeeks
Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.
int
findSum(string str)
{
// A temporary string
string temp =
""
;
// holds sum of all numbers present in the string
int
sum = 0;
// read each charcater in input string
for
(
char
ch: str)
{
// if current character is a digit
if
(
isdigit
(ch))
temp += ch;
// if current character is an alphabet
else
{
// increment sum by number found earlier
// (if any)
sum +=
atoi
(temp.c_str());
// reset temporary string to empty
temp =
""
;
}
}
// atoi(temp.c_str()) takes care of trailing
// numbers
return
sum +
atoi
(temp.c_str());
}