Hazem Alabiad Hazem Alabiad - 1 year ago 79
C Question

Extract all numbers of N digits from a string in C

I want to get all numbers from a specific string but, these numbers could be more than one digit long as (15, 587, ... exc). Here is what I did "my own code":

int firstIndxOfNumb(char* str, int startIndx, int len) {
int i, val;
i = startIndx;
while (str[i] && i < len) {
val = str[i];
if (isdigit(val))
return i;
return -1;

int lastIndxOfNumb(char* exp, int len, int indx1){
int i, curr;
for(i = indx1; i < len; i++){
curr = exp[i];
return --i;
return 0;

int getNumb(char* exp, int len, int* indx1){
int indx2 = lastIndxOfNumb(exp, len, *indx1);

printf("indx1:%d\tindx2:%d\n", *indx1, indx2);

char temp[indx2-*indx1];
strncpy(temp, exp+*indx1, (size_t) (indx2-*indx1+1));
*indx1 = firstIndxOfNumb(exp, indx2+1, len);
return atoi(temp);

void main() {
char *s = "())(15*59";
int len = strlen(s);
int indx1;
indx1 = firstIndxOfNumb(s, 0, len);
printf("%d\n", getNumb(s, len, &indx1));
printf("\n%d", getNumb(s, len, &indx1));


And the goal is getting the two numbers (15, 59). The first call was okay but, the second is not "infinite-loop" with values index1:7 okay index2:0 isn't okay! Can you help me to make it working .....

The values are printed by
function ....

Answer Source

getNumb can be simplified as follows.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int getNumb(char **sp){
    char *p = *sp;
    while(*p && !isdigit((unsigned char)*p))//skip not digit
        return -1;//not find numbers (Don't include negative numbers as extract numbers)
    int ret = strtol(p, &p, 10);
    *sp = p;
    return ret;

int main(void) {
    char *s = "())(15*59";
    char *sp = s;
    printf("%d\n", getNumb(&sp));
    printf("%d\n", getNumb(&sp));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download