Home > Software design >  To find the sum of all int present in a string
To find the sum of all int present in a string

Time:12-07

#include <string>
#include<ctype.h>

using namespace std;

int main(){

string s="124j3a.n2-'ad2'&1#vvg6";

string a="";

int digit,sum(0),temp;

for(char c:s){
     if(isdigit(c)){
       a =c;    
    }   
}
digit=stoi(a); 

while (digit>0)
{
  temp=digit%10;
  sum =temp;
  digit/=10;
}
cout<<sum;
    return 0;
}

so in this case the output sum will be 21 (1 2 4 3 2 2 1 6)

I've written this solution and code is working fine but is there a better way to find the sum of all integers present in string s.

CodePudding user response:

Instead of appending each digit you find to a string and calculating it afterwards, you could immediately sum the found digits.

for (char c : s) {
  if (isdigit(c)) {
    sum  = stoi(c);    
  }   
}

cout << sum;

CodePudding user response:

You can take advantage of the fact that a single char containing a digit can be easily converted to an integer value by subtracting '0' from it.

int sum{0};
for (char c : s) {
    if (isdigit(c)) {
        sum  = c - '0';
    }
}
  • Related