Q:在一个string中,将所有digits相加,如abc12ab1ab1234,应该得到12+1+1234=1237
A:
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int checkAlpha(char *str)
{
if((*str <= 'Z' && *str >= 'A') || (*str <= 'z' && *str >= 'a'))
return 1;
else
return 0;
}
int sum (char* str)
{
int sum = 0;
while(*str != '\0'){
if(checkAlpha(str)){
str++;
continue;
}
else{
int tmp = 0;
int len = 1;
while(len){
if(*(str+len) != '\0' && !checkAlpha(str+len)){
len++;
continue;
}
else
break;
}
//the num length is len
int i;
for(i = 0; i < len; i++){
tmp = tmp*10 + (*(str+i) - '0');
}
sum += tmp;
str += len;
}
}
return sum;
}
int main(int argc, char *argv[])
{
char *b = "abc100ab1ab2a1";
printf("%d\n",sum(b));
}