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++
#include <iostream>
using namespace std;
int findSum(string str)
{
string temp = "" ;
int sum = 0;
for ( char ch : str) {
if ( isdigit (ch))
temp += ch;
else {
sum += atoi (temp.c_str());
temp = "" ;
}
}
return sum + atoi (temp.c_str());
}
int main()
{
string str = "12abc20yz68" ;
cout << findSum(str);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int findSum(String str)
{
String temp = "0" ;
int sum = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isDigit(ch))
temp += ch;
else {
sum += Integer.parseInt(temp);
temp = "0" ;
}
}
return sum + Integer.parseInt(temp);
}
public static void main(String[] args)
{
String str = "12abc20yz68" ;
System.out.println(findSum(str));
}
}
|
Python3
def findSum(str1):
temp = "0"
Sum = 0
for ch in str1:
if (ch.isdigit()):
temp + = ch
else :
Sum + = int (temp)
temp = "0"
return Sum + int (temp)
str1 = "12abc20yz68"
print (findSum(str1))
|
C#
using System;
class GFG {
static int findSum(String str)
{
String temp = "0" ;
int sum = 0;
for ( int i = 0; i < str.Length; i++) {
char ch = str[i];
if ( char .IsDigit(ch))
temp += ch;
else {
sum += int .Parse(temp);
temp = "0" ;
}
}
return sum + int .Parse(temp);
}
public static void Main(String[] args)
{
String str = "12abc20yz68" ;
Console.WriteLine(findSum(str));
}
}
|
Javascript
<script>
function findSum(str)
{
let temp = "0" ;
let sum = 0;
for (let i = 0; i < str.length; i++) {
let ch = str[i];
if (!isNaN(String(ch) * 1))
temp += ch;
else {
sum += parseInt(temp);
temp = "0" ;
}
}
return sum + parseInt(temp);
}
let str = "12abc20yz68" ;
document.write(findSum(str));
</script>
|
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 j 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++
#include <iostream>
using namespace std;
int solve(string& str, int i, int n)
{
if (i >= n)
return 0;
if (i == n - 1) {
if ( isdigit (str[i])) {
return str[i] - '0' ;
}
else {
return 0;
}
}
if ( isdigit (str[i])) {
string temp = "" ;
int j;
for (j = i; j < n; j++) {
if ( isdigit (str[j]))
temp += str[j];
else
break ;
}
return stoi(temp) + solve(str, j, n);
}
else {
solve(str, i + 1, n);
}
}
int findSum(string str)
{
return solve(str, 0, str.size());
}
int main()
{
string str = "12abc20yz68" ;
cout << findSum(str);
return 0;
}
|
Java
import java.util.Scanner;
class Main {
static int solve(String str, int i, int n) {
if (i >= n)
return 0 ;
if (i == n - 1 ) {
if (Character.isDigit(str.charAt(i))) {
return str.charAt(i) - '0' ;
}
else {
return 0 ;
}
}
if (Character.isDigit(str.charAt(i))) {
String temp = "" ;
int j;
for (j = i; j < n; j++) {
if (Character.isDigit(str.charAt(j)))
temp += str.charAt(j);
else
break ;
}
return Integer.parseInt(temp) + solve(str, j, n);
}
else {
return solve(str, i + 1 , n);
}
}
static int findSum(String str) {
return solve(str, 0 , str.length());
}
public static void main(String[] args) {
String str = "12abc20yz68" ;
System.out.println(findSum(str));
}
}
|
Python3
def findSum( str ):
result = 0
temp = ""
for i in range ( len ( str )):
if str [i].isnumeric():
temp + = str [i]
if i = = len ( str ) - 1 :
result + = int (temp)
else :
if temp ! = "":
result + = int (temp)
temp = ""
return result
if __name__ = = "__main__" :
str = "12abc20yz68"
print (findSum( str ))
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
static bool isdigit( char c)
{
if (c>= '0' && c<= '9' )
return true ;
return false ;
}
static int solve( string str, int i, int n)
{
if (i >= n)
return 0;
if (i == n - 1) {
if (isdigit(str[i])) {
return str[i];
}
else {
return 0;
}
}
if (isdigit(str[i])) {
string temp = "" ;
int j;
for (j = i; j < n; j++) {
if (isdigit(str[j]))
temp += str[j];
else
break ;
}
return Int32.Parse(temp) + solve(str, j, n);
}
else {
return solve(str, i + 1, n);
}
}
static int findSum( string str)
{
return solve(str, 0, str.Length);
}
static public void Main()
{
string str = "12abc20yz68" ;
Console.Write(findSum(str));
}
}
|
Javascript
function findSum(str) {
let result = 0;
let temp = "" ;
for (let i = 0; i < str.length; i++) {
if (!isNaN(str[i])) {
temp += str[i];
if (i === str.length - 1) {
result += parseInt(temp);
}
} else {
if (temp !== "" ) {
result += parseInt(temp);
temp = "" ;
}
}
}
return result;
}
console.log(findSum( "12abc20yz68" ));
|
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:
C++14
#include <iostream>
#include <regex>
int findSum(std::string str) {
std::regex pattern( "\\d+" );
std::smatch match;
int sum = 0;
while (std::regex_search(str, match, pattern)) {
sum += stoi(match[0].str());
str = match.suffix().str();
}
return sum;
}
int main() {
std::string str = "12abc20yz68" ;
std::cout << findSum(str) << std::endl;
return 0;
}
|
Python3
import re
def find_sum(str1):
return sum ( map ( int , re.findall( '\d+' , str1)))
str1 = "12abc20yz68"
print (find_sum(str1))
|
Javascript
function find_sum(str1) {
return str1.match(/\d+/g).reduce((acc, val) => acc + parseInt(val), 0);
}
const str1 = "12abc20yz68" ;
console.log(find_sum(str1));
|
Java
import java.util.regex.*;
public class Main {
public static int findSum(String str)
{
Pattern pattern = Pattern.compile( "\\d+" );
Matcher matcher = pattern.matcher(str);
int sum = 0 ;
while (matcher.find()) {
sum += Integer.parseInt(matcher.group());
str = matcher.replaceFirst( "" );
matcher = pattern.matcher(str);
}
return sum;
}
public static void main(String[] args)
{
String str = "12abc20yz68" ;
System.out.println(findSum(str));
}
}
|
C#
using System;
using System.Text.RegularExpressions;
public class GFG
{
public static int FindSum( string str)
{
Regex pattern = new Regex( @"\d+" );
Match matcher = pattern.Match(str);
int sum = 0;
while (matcher.Success)
{
sum += Int32.Parse(matcher.Value);
str = pattern.Replace(str, "" , 1, matcher.Index);
matcher = pattern.Match(str);
}
return sum;
}
static public void Main()
{
string str = "12abc20yz68" ;
Console.WriteLine(FindSum(str));
}
}
|
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.