Home » Interview Questions » String Interview Questions » Calculate sum of all numbers present in a string

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


s = “12bc1nk8”

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


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
            // 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


How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Word Break
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions