C++ Exercises: Find the numbers in a given string and calculate the sum of all numbers
C++ String: Exercise-14 with Solution
Write a C++ program to find the numbers in a given string and calculate the sum of all numbers.
Pictorial Presentation:
Sample Solution:
C++ Code :
#include <iostream>
#include <string>
using namespace std;
int find_nums_and_sum(string str) {
int sum_num = 0;
string temp_str;
for (int x = 0; x < str.length(); x++)
{
if (isdigit(str[x]))
{
temp_str.push_back(str[x]);
for (int y = x + 1; y < str.length(); y++)
{
if (y >= str.length())
{
break;
}
else if (isdigit(str[y]))
{
temp_str.push_back(str[y]);
x = y;
}
else
{
break;
}
}
sum_num += stoi(temp_str);
temp_str.clear();
}
}
return sum_num;
}
int main() {
cout << "Original string: 91, ABC Street.-> Sum of the numbers: "<< find_nums_and_sum("91, ABC Street.") << endl;
cout << "Original string: w3resource from 2008-> Sum of the numbers: "<< find_nums_and_sum("w3resource from 2008") << endl;
cout << "Original string: C++ Versiuon 14aa11bb23-> Sum of the numbers: "<< find_nums_and_sum("C++ Versiuon 14aa11bb23") << endl;
return 0;
}
Sample Output:
Original string: 91, ABC Street.-> Sum of the numbers: 91 Original string: w3resource from 2008-> Sum of the numbers: 2011 Original string: C++ Versiuon 14aa11bb23-> Sum of the numbers: 48
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to change the case (lower to upper and upper to lower cases) of each character of a given string.
Next: Write a C++ program to convert a givern non-negative integer to english words.
What is the difficulty level of this exercise?