Calcular la suma de todos los números presentes en una string

Dada una string que contiene caracteres alfanuméricos, calcule la suma de todos los números presentes en la string.

Ejemplos: 

Input:  1abc23
Output: 24

Input:  geeks4geeks
Output: 4

Input:  1abc2x30yz67
Output: 100

Input:  123abc
Output: 123

Nivel de dificultad: Novato

La única parte complicada de esta pregunta es que varios dígitos consecutivos se consideran como un solo número.
La idea es muy simple. Escaneamos cada carácter de la string de entrada y si un número está formado por caracteres consecutivos de la string, incrementamos el resultado en esa cantidad. 

A continuación se muestra la implementación de la idea anterior:

C++

// 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 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
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

<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>
Producción

100

Complejidad temporal: O(n) donde n es la longitud de la string. 
Espacio auxiliar: O(n) donde n es la longitud de la string.

Una mejor solución implementando 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 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
Producción

100

Complejidad temporal: O(n) donde n es la longitud de la string. 
Espacio auxiliar: O(n) donde n es la longitud de la string.

Este artículo es una contribución de Aditya Goel . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *