Calculate sum of all numbers present in a string

Given a string of alpha numeric characters, write a function that will calculate all the numbers present in that string

Example

INPUT
s = "12bc1nk8"

OUTPUT
21
In the above example the sum is 12+1+8 = 21

Algorithm

1. Traverse through the given string

2. If a number is formed with the consecutive characters, then add that to the previous sum

C++ Program

#include <bits/stdc++.h>
using namespace std;
 
//Calculates the sum
int sumInString(string s)
{
    string temp = "";
    int n = s.length();
 
    // sum of all numbers in string
    int result = 0;
 
    // scan each charcater in input string
    for (int i =0; i<n; i++)
    {
        // if character is a digit
        if (isdigit(s[i]))
            temp += s[i];
 
        // if current character is an alphabet
        else
        {
            // increment result by number found earlier
            // (if any)
            result += atoi(temp.c_str());
 
            // reset temporary string to empty
            temp = "";
        }
    }
 
    // atoi(temp.c_str()) takes care of trailing
    // numbers
    return result + atoi(temp.c_str());
}
 

int main()
{
    string s = "12bc1nk8";
    cout << sumInString(s)<<endl;
 
    return 0;
}
Try It

 


Next > < Prev
Scroll to Top