Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

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 112 views
1 answer 128 views
1 answer 92 views
1 answer 127 views
1 answer 91 views
...