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


Leave a Comment

Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions
Core Java Interview Questions