C++ Program to Count the Sum of Numbers in a String




In this problem, we are given a string containing alphanumeric characters, and the task is to extract all the numbers from the string and compute their sum. The numbers may appear anywhere within the string, and we need to identify them and add them together. In this article, we are going to explore different approaches to solving this problem in C++.




Example 1


Input:

str = "anshu123ayush45anshu"


Output:

Sum = 174

Explanation:


The numbers extracted from the string are 123, 45, and 6. Their sum is 123 + 45 + 6 = 174.





Example 2


Input:

str = "1abc2def34ghi56jkl"


Output:

Sum = 93

Explanation:


The numbers extracted from the string are 1, 2, 34, and 56. Their sum is 1 + 2 + 34 + 56 = 93.




Below are different approaches to counting the sum of numbers in a string:




Using the Brute Force Approach


This is the simplest and most direct approach for extracting numbers from a string and calculating their sum. We traverse the string character by character and extract numeric digits. Once we find a non-numeric character, we convert the collected digits into a number and add it to the sum. Return the sum.


Steps for Implementation

  • Initialize a variable to store the sum.
  • Traverse through each character of the string.
  • If the character is a digit, append it to a temporary string.
  • If a non-digit character is encountered, convert the collected digits into a number and add it to the sum.
  • Repeat the process until the end of the string.
  • Print the final sum.


Implementation Code


#include<bits/stdc++.h>
using namespace std;

int sumOfNumbersBruteForce(string str) {
int sum = 0, num = 0;
for (char ch : str) {
if (isdigit(ch)) {
num = num * 10 + (ch - '0');
} else {
sum += num;
num = 0;
}
}
sum += num; // Add the last number if any
return sum;
}

int main() {
string str = "abc123xyz45mno6";
cout << "Sum of numbers in string: " << sumOfNumbersBruteForce(str);
return 0;
}



Output

Sum of numbers in string: 174


Time Complexity:

O(N)


Space Complexity:

O(1)




Using the String Stream Approach



In this approach, we use stringstream to extract numbers from the given string. The stringstream class allows us to process the string as if it were a stream of characters.


Steps for Implementation

  • Create a stringstream object from the input string.
  • Extract characters one by one.
  • If a digit is found, append it to a temporary string.
  • If a non-digit character is encountered, convert the temporary string into a number and add it to the sum.
  • Print the final sum.



Implementation Code

#include<bits/stdc++.h>
using namespace std;

int sumOfNumbersUsingStringStream(string str) {
stringstream ss;
int sum = 0;
string temp;

for (char ch : str) {
if (isdigit(ch)) {
ss << ch; // Add digit to stringstream
} else {
if (!ss.str().empty()) { // If ss is not empty, extract the number
sum += stoi(ss.str());
ss.str(""); // Clear the stringstream
ss.clear(); // Reset error flags
}
}
}

// Add the last number (if any) in the string
if (!ss.str().empty()) {
sum += stoi(ss.str());
}

return sum;
}

int main() {
string str = "1abc2def34ghi56jkl";
cout << "Sum of numbers in string: " << sumOfNumbersUsingStringStream(str) << endl;
return 0;
}


Output:


Sum of numbers in string: 93



Time Complexity:

O(N)


Space Complexity:

O(1)



Using Regular Expressions (Regex) Approach


This is a more advanced approach where we use regular expressions (regex) to extract all numbers from the string and calculate their sum.

Steps for Implementation

  • Create a regex pattern to find numbers.
  • Use regex_search to extract all numbers from the string.
  • Convert the extracted numbers to integers and compute the sum.
  • Print the final sum.


Implementation Code

#include<bits/stdc++.h>
using namespace std;

int sumOfNumbersUsingRegex(string str) {
regex pattern("\d+");
sregex_iterator it(str.begin(), str.end(), pattern);
sregex_iterator end;
int sum = 0;
while (it != end) {
sum += stoi(it->str());
++it;
}
return sum;
}

int main() {
string str = "abc100xyz20pq30";
cout << "Sum of numbers in string: " << sumOfNumbersUsingRegex(str);
return 0;
}




Output:

Sum of numbers in string: 150



Time Complexity:

O(N)



Space Complexity:

O(N)

Updated on: 2025-03-18T08:20:46+05:30

1 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements