How to extract the number from the end of a string in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int extractLastNumber(const char* str) {
    size_t i = strlen(str);

    while (i > 0 && isdigit(str[i - 1])) {
        i--;
    }

    return atoi(&str[i]);
}

int main() {
    const char* str = "c 23 programming18710";

    int n = extractLastNumber(str);

    printf("%d\n", n);
}



/*
run:

18710

*/

 



answered Aug 17, 2024 by avibootz

Related questions

1 answer 122 views
2 answers 127 views
2 answers 129 views
2 answers 129 views
2 answers 137 views
2 answers 124 views
...