## Related Articles

• Write an Interview Experience
• String Data Structure

# Calculate sum of all numbers present in a string

• Difficulty Level : Easy
• Last Updated : 20 Sep, 2022

Given a string S containing alphanumeric characters, The task is to calculate the sum of all numbers present in the string.

Examples:

Input:  1abc23
Output: 24
Explanation: 1 + 23 = 24

Input:  geeks4geeks
Output: 4

Input:  1abc2x30yz67
Output: 100

## Approach:

Scan each character of the input string and if a number is formed by consecutive characters of the string, then increment the result by that amount. The only tricky part of this question is that multiple consecutive digits are considered one number.

Follow the below steps to implement the idea:

• Create an empty string temp and an integer sum.
• Iterate over all characters of the string.
• If the character is a numeric digit add it to temp.
• Else convert temp string to number and add it to sum, empty temp.
• Return sum + number obtained from temp.

Below is the implementation of the above approach:

## C++

 `// C++ program to calculate sum of all numbers present``// in a string containing alphanumeric characters``#include ``using` `namespace` `std;` `// Function to calculate sum of all numbers present``// in a string containing alphanumeric characters``int` `findSum(string str)``{``    ``// A temporary string``    ``string temp = ``""``;` `    ``// holds sum of all numbers present in the string``    ``int` `sum = 0;` `    ``// read each character in input string``    ``for` `(``char` `ch : str) {``        ``// if current character is a digit``        ``if` `(``isdigit``(ch))``            ``temp += ch;` `        ``// if current character is an alphabet``        ``else` `{``            ``// increment sum by number found earlier``            ``// (if any)``            ``sum += ``atoi``(temp.c_str());` `            ``// reset temporary string to empty``            ``temp = ``""``;``        ``}``    ``}` `    ``// atoi(temp.c_str()) takes care of trailing``    ``// numbers``    ``return` `sum + ``atoi``(temp.c_str());``}` `// Driver code``int` `main()``{``    ``// input alphanumeric string``    ``string str = ``"12abc20yz68"``;` `    ``// Function call``    ``cout << findSum(str);` `    ``return` `0;``}`

## Java

 `// Java program to calculate sum of all numbers present``// in a string containing alphanumeric characters``import` `java.io.*;` `class` `GFG {` `    ``// Function to calculate sum of all numbers present``    ``// in a string containing alphanumeric characters``    ``static` `int` `findSum(String str)``    ``{``        ``// A temporary string``        ``String temp = ``"0"``;` `        ``// holds sum of all numbers present in the string``        ``int` `sum = ``0``;` `        ``// read each character in input string``        ``for` `(``int` `i = ``0``; i < str.length(); i++) {``            ``char` `ch = str.charAt(i);` `            ``// if current character is a digit``            ``if` `(Character.isDigit(ch))``                ``temp += ch;` `            ``// if current character is an alphabet``            ``else` `{``                ``// increment sum by number found earlier``                ``// (if any)``                ``sum += Integer.parseInt(temp);` `                ``// reset temporary string to empty``                ``temp = ``"0"``;``            ``}``        ``}` `        ``// atoi(temp.c_str()) takes care of trailing``        ``// numbers``        ``return` `sum + Integer.parseInt(temp);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{` `        ``// input alphanumeric string``        ``String str = ``"12abc20yz68"``;` `        ``// Function call``        ``System.out.println(findSum(str));``    ``}``}` `// This code is contributed by AnkitRai01`

## Python3

 `# Python3 program to calculate sum of``# all numbers present in a string``# containing alphanumeric characters` `# Function to calculate sum of all``# numbers present in a string``# containing alphanumeric characters`  `def` `findSum(str1):` `    ``# A temporary string``    ``temp ``=` `"0"` `    ``# holds sum of all numbers``    ``# present in the string``    ``Sum` `=` `0` `    ``# read each character in input string``    ``for` `ch ``in` `str1:` `        ``# if current character is a digit``        ``if` `(ch.isdigit()):``            ``temp ``+``=` `ch` `        ``# if current character is an alphabet``        ``else``:` `            ``# increment Sum by number found``            ``# earlier(if any)``            ``Sum` `+``=` `int``(temp)` `            ``# reset temporary string to empty``            ``temp ``=` `"0"` `    ``# atoi(temp.c_str1()) takes care``    ``# of trailing numbers``    ``return` `Sum` `+` `int``(temp)` `# Driver code`  `# input alphanumeric string``str1 ``=` `"12abc20yz68"` `# Function call``print``(findSum(str1))` `# This code is contributed``# by mohit kumar`

## C#

 `// C# program to calculate sum of``// all numbers present in a string``// containing alphanumeric characters``using` `System;` `class` `GFG {` `    ``// Function to calculate sum of``    ``// all numbers present in a string``    ``// containing alphanumeric characters``    ``static` `int` `findSum(String str)``    ``{``        ``// A temporary string``        ``String temp = ``"0"``;` `        ``// holds sum of all numbers``        ``// present in the string``        ``int` `sum = 0;` `        ``// read each character in input string``        ``for` `(``int` `i = 0; i < str.Length; i++) {``            ``char` `ch = str[i];` `            ``// if current character is a digit``            ``if` `(``char``.IsDigit(ch))``                ``temp += ch;` `            ``// if current character is an alphabet``            ``else` `{` `                ``// increment sum by number found earlier``                ``// (if any)``                ``sum += ``int``.Parse(temp);` `                ``// reset temporary string to empty``                ``temp = ``"0"``;``            ``}``        ``}` `        ``// atoi(temp.c_str()) takes care of trailing``        ``// numbers``        ``return` `sum + ``int``.Parse(temp);``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(String[] args)``    ``{` `        ``// input alphanumeric string``        ``String str = ``"12abc20yz68"``;` `        ``// Function call``        ``Console.WriteLine(findSum(str));``    ``}``}` `// This code is contributed by PrinciRaj1992`

## Javascript

 ``

Output

`100`

Time complexity: O(N) where n is length of the string.
Auxiliary Space: O(N) where n is length of the string.

## Calculate sum of all numbers present in a string using recursion

The idea is to recursively traverse over the string and find out the numbers then add these numbers to the result, at last return the result

Follow the below steps to implement the idea:

• Create an empty string temp and an integer sum.
• Recursively traverse the characters for every index i from 0 to length – 1.
• If i = N-1 then check if current character is a digit return str[i] – ‘0’.
• Else return 0.
• If str[i] is a digit.
• Run a for loop with counter from i to N – 1.
• If the character is a numeric digit add it to temp.
• Else break.
• Return sum of numeric value of temp + recur for index j.

Below is the implementation of the above approach:

## C++

 `// C++ program to calculate sum of all numbers``// present in a string containing alphanumeric``// characters``#include ``using` `namespace` `std;` `int` `solve(string& str, ``int` `i, ``int` `n)``{``    ``// if string is empty``    ``if` `(i >= n)``        ``return` `0;` `    ``// if on the last index``    ``if` `(i == n - 1) {` `        ``// if last digit is numeric``        ``if` `(``isdigit``(str[i])) {``            ``return` `str[i] - ``'0'``;``        ``}``        ``else` `{``            ``return` `0;``        ``}``    ``}` `    ``// if current char is digit``    ``// then sum the consecutive digits``    ``if` `(``isdigit``(str[i])) {` `        ``// declared an empty string``        ``string temp = ``""``;``        ``int` `j;` `        ``// start from that index``        ``// sum all the consecutive digits``        ``for` `(j = i; j < n; j++) {` `            ``// if current char is digit``            ``// add it to the temp string``            ``if` `(``isdigit``(str[j]))``                ``temp += str[j];` `            ``// if it is not a digit``            ``// break instantly``            ``else``                ``break``;``        ``}` `        ``// add the number associated to temp``        ``// with the answer recursion will bring``        ``return` `stoi(temp) + solve(str, j, n);``    ``}` `    ``// else call from the next index``    ``else` `{``        ``solve(str, i + 1, n);``    ``}``}` `int` `findSum(string str)``{``    ``// recursiven function``    ``return` `solve(str, 0, str.size());``}` `// Driver code``int` `main()``{``    ``// input alphanumeric string``    ``string str = ``"12abc20yz68"``;` `    ``// Function call``    ``cout << findSum(str);` `    ``return` `0;``}`

Output

`100`

Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(N), in worst case it can cost O(N) recursive calls

## Calculate sum of all numbers present in a string using Regex in Python:

The idea is to use inbuilt function Python RegEx

Below is the Implementation of above approach:

## Python3

 `# Python3 program to calculate sum of``# all numbers present in a string``# containing alphanumeric characters` `# Function to calculate sum of all``# numbers present in a string``# containing alphanumeric characters``import` `re`  `def` `find_sum(str1):``    ``# Regular Expression that matches``    ``# digits in between a string``    ``return` `sum``(``map``(``int``, re.findall(``'\d+'``, str1)))` `# Driver code``# input alphanumeric string``str1 ``=` `"12abc20yz68"` `# Function call``print``(find_sum(str1))` `# This code is contributed``# by Venkata Ramana B`

Output

```100
```

Time complexity: O(n) where n is length of the string.
Auxiliary Space: O(n) where n is length of the string.