How to extract number from a string in C

2 Answers

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

int get_number(char s[])
{
    int n = 0;
    for (int i = 0; i < strlen(s); i++) {
       if (isdigit(s[i]))
            n = n * 10 + (s[i] - '0');
    }
    return n;
}

int main()
{
    char s[] = "abcd 89 efghi";

    printf("%d\n", get_number(s));
    
    return 0;
}

/*
run:
 
89

*/

 



answered May 26, 2018 by avibootz
0 votes
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int get_number(char s[])
{
    int n = 0;
    for (int i = 0; i < strlen(s); i++) {
       if (isdigit(s[i]))
            n = n * 10 + (s[i] - '0');
    }
    return n;
}

int main()
{
    char s[] = "abcd981efghi";

    printf("%d\n", get_number(s));
    
    return 0;
}

/*
run:
 
981

*/

 



answered May 27, 2018 by avibootz

Related questions

1 answer 109 views
2 answers 165 views
1 answer 184 views
1 answer 121 views
1 answer 122 views
...