Calculate sum of all numbers present in a string

04 Jul, 2022
Given a string containing alphanumeric characters, calculate sum of all numbers present in the string.
Examples: 
Input:  1abc23
Output: 24

Input:  geeks4geeks
Output: 4

Input:  1abc2x30yz67
Output: 100

Input:  123abc
Output: 123
Difficulty level: Rookie
The only tricky part in this question is that multiple consecutive digits are considered as one number.The idea is very simple. We scan each character of the input string and if a number is formed by consecutive characters of the string, we increment the result by that amount. 
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// C++ program to calculate sum of all numbers present// in a string containing alphanumeric characters#include <iostream>using namespace std; // Function to calculate sum of all numbers present// in a string containing alphanumeric charactersint 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 codeint main(){    // input alphanumeric string    string str = "12abc20yz68";     // Function call    cout << findSum(str);     return 0;}
// Java program to calculate sum of all numbers present// in a string containing alphanumeric charactersclass 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 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 stringstr1 = "12abc20yz68" # Function callprint(findSum(str1)) # This code is contributed# by mohit kumar
// C# program to calculate sum of// all numbers present in a string// containing alphanumeric charactersusing 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
<script> // Javascript 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    function findSum(str)    {        // A temporary string        let temp = "0";           // holds sum of all numbers        // present in the string        let sum = 0;           // read each character in input string        for (let i = 0; i < str.length; i++) {            let ch = str[i];               // if current character is a digit            if (!isNaN(String(ch) * 1))                temp += ch;               // if current character is an alphabet            else {                // increment sum by number found earlier                // (if any)                sum += parseInt(temp);                   // reset temporary string to empty                temp = "0";            }        }           // atoi(temp.c_str()) takes care of trailing        // numbers        return sum + parseInt(temp);    }         // Driver code    // input alphanumeric string    let str = "12abc20yz68";         // Function call    document.write(findSum(str));      // This code is contributed by unknown2108 </script>
100
Time complexity: O(n) where n is length of the string. Auxiliary Space: O(n) where n is length of the string.
A Better Solution implementing Regex.
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 charactersimport 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 stringstr1 = "12abc20yz68" # Function callprint(find_sum(str1)) # This code is contributed# by Venkata Ramana B
100
Time complexity: O(n) where n is length of the string. Auxiliary Space: O(n) where n is length of the string.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
mohit kumar 29
iskra
nidhi_biet
ankthon
princiraj1992
shrey_shreyansh
unknown2108
simmytarika5
anandkumarshivam2266
hardikkoriintern
Amazon
Linkedin
MAQ Software
SAP Labs
Strings
Amazon
MAQ Software
SAP Labs
Linkedin
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++
Longest Common Subsequence | DP-4
Python program to check if a string is palindrome or not
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews