Program to find the sum of all numbers present in the string | faceprep

Program to find the sum of all numbers present in the string is discussed here. Given a string containing both numbers and alphabets, the task is to find the sum of all numbers present in the string.

For example, consider the string

Input: abc45def5ghi32

Output: 82

Explanation: 

The numbers 45, 5 and 32 are present in the string.

Sum = 45 + 5 + 32 = 82.

Algorithm to find the sum of all numbers present in the string

  • Input the string from the user.
  • Initialize sum = 0.
  • FInd the numbers that are present in the string and add it with sum.
  • Display sum.

Program to find the sum of all numbers present in the string is given below.

/* C++ program to find the sum of all numbers present in the string */
#include <bits/stdc++.h>
using namespace std;
// Function to find the sum of all  numbers present in the string
int calculate_sum(string str)
{
string temp = “”;   // intitialize temp
int sum = 0;  // initialize sum
for (char ch: str)   // traverse the characters one by one
{
if (isdigit(ch))  // if the character is a digit
temp += ch;  // add that character to temp
else
{
sum += atoi(temp.c_str());  // add it with sum
temp = “”;
}
}
return sum + atoi(temp.c_str());  // return the sum
}
int main()
{
string str;
cin >> str;  // input the string from the user.
cout << calculate_sum(str);
return 0;
}

# Pyhton program to find the sum of all numbers present in the string
# Function to find the sum of all numbers in the string
def findSum(str1):
temp = “”  # initialize temp
sum = 0  #initialize sum
for ch in str1:  # Traverse the characters one by one
if (ch.isdigit()):   # if the character is a sigit
temp += ch  # add that char to the string temp
else:
sum = sum + int(temp)  # find the sum of all numbers in string temp
temp = “0”
return sum + int(temp)  # return the sum
str1 = input(“Enter the string : “)
print(findSum(str1))

Output:

sum of all numbers present in the string