Find the sum of the numbers in the sequence

54 views Asked by At

Input a string and print the sum of the numbers in the string

Input: abc123kjewd456

Output: 579

I want code it with pointer in string, array, loop, and lots of way, Can you help me use the best way? .

1

There are 1 answers

0
mohamed ahmed On
int sumInString(const char *str) {
  // valid str
  if (str == NULL || *str == '\0') {
    return 0;
  }
  int num = 0;
  int res = 0;
  int i = 0;
  while (str[i] != '\0') {
    if (str[i] >= '0' && str[i] <= '9') /*is numerical*/ {
      num *= 10;
      num += str[i] - '0'; // char->int conversion
    } else {
      res += num;
      num = 0;
    }
    ++i;
  }
  res += num; // add the remainder
  return res;
}