Sum of numbers formed by consecutive digits present in a given string | C ++ Program to implement the above approach ; Function to calculate the sum of numbers formed by consecutive sequences of digits present in the string ; Stores consecutive digits present in the string ; Stores the sum ; Iterate over characters of the input string ; If current character is a digit ; Append current digit to curr ; Add curr to sum ; Reset curr ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigits ( string s ) { int curr = 0 ; int ret = 0 ; for ( auto & ch : s ) { if ( isdigit ( ch ) ) { curr = curr * 10 + ch - '0' ; } else { ret += curr ; curr = 0 ; } } ret += curr ; return ret ; } int main ( ) { string S = "11aa32bbb5" ; cout << sumOfDigits ( S ) ; return 0 ; }