How to extract the last number from a string in C

2 Answers

0 votes
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> 
 
// long int strtol(const char *str, char **endptr, int base)
 
int extract_last_numbers(char *str) {
    char *p = str;
     
    while (*p) { 
        if (isdigit(*p) || ((*p == '-' || *p == '+') && isdigit(*(p + 1)))) {
            return strtol(p, &p, 10); 
        } else {
            p++;
        }
    }
    
    return -1;
}
 
int main() {
    char *str = "c programming 12";
     
    printf("%d", extract_last_numbers(str));
 
    return 0;
}
 
 
 
 
/*
run:
 
12

*/

 



answered Aug 29, 2023 by avibootz
edited Aug 29, 2023 by avibootz
0 votes
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> 
 
// long int strtol(const char *str, char **endptr, int base)
 
int extract_last_numbers(char *str) {
    char *p = str;
    int number = -1;
     
    while (*p) { 
        if (isdigit(*p) || ((*p == '-' || *p == '+') && isdigit(*(p + 1)))) {
            number = strtol(p, &p, 10); 
        } else {
            p++;
        }
    }
    
    return number;
}
 
int main() {
    char *str = "98 c programming 12";
     
    printf("%d", extract_last_numbers(str));
 
    return 0;
}
 
 
 
 
/*
run:
 
12

*/

 



answered Aug 30, 2023 by avibootz

Related questions

1 answer 130 views
1 answer 151 views
1 answer 114 views
1 answer 139 views
1 answer 113 views
...