How to extract numbers from a string in C?

how to extract numbers from a string in C

In this article, you’ll learn how to get numbers from a string in C with examples. There are many ways to do that, but my favorite a recommended method is by using strtol() for converting string to integer and strtof() for converting string into floating point numbers.

How to extract numbers from string in C?

Simple answer: Use strtol() or strtof() functions alongwith isdigit() function.

Example 1: C program to print the integers in a string: Reading integers from string in C

#include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
     
    int main(void) {
        char *str = "programmingarticles2test#5/-", *p = str;
        float arr[10];
        while (*p) {
            if (isdigit(*p)) {
                long val = strtol(p, &p, 10);
                printf("%ld\n", val);
            } else {
                p++;
            }
        }
        return 0;
    }

Output:

2
5

Example 2: C program to print the sum of numbers in a string: Extract floating point numbers from a string in C

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
    
int main(void) {
    char *str = "progr34.2amming-articles9.7com", *p = str;
    float arr[10], sum = 0;
    while (*p) {
        if (isdigit(*p)) {
            float val = strtof(p, &p);
            sum += val;
        } else {
            p++;
        }
    }
    printf("%.2lf\n", sum);
    return 0;
}

Output:

43.90

Example 3: A question that I got asked on Facebook by a programming student.

Problem: Two runners are racing against each other in the 400 meter dash and you want to know who will win. The current distance covered by each runner(meters) and the speed (meters per second) will be given for each runner. Return whether the first or the second runner will end up winning the race assuming they travel at the speed throughout the remainder of the race.

There are more details to the question, but this is more than enough to understand the problem statement here.

Solution in C: Approach the solution the same way used above.

I’ve also added the sample input accordingly, therefore use this as a reference only. Try to learn how it’s done and implement that in your code.

#include<stdio.h>
#include <stdlib.h>
#include <ctype.h>
float timeTaken(char *, float);
int main()
{
    float dist_total = 400;     //you can remove this if total distance is considered to be fixed.
    char input1[] = "runner 1 is traveling at 10.5 meters per second and has already covered 100.0 meters";
    char input2[] = "runner 2 is traveling at 9.3 meters per second and has already covered 300 meters";
    
    float timeX = timeTaken(input1, dist_total);
    float timeY = timeTaken(input2, dist_total);

    if(timeX > timeY)
    {
        printf("Runner 2 wins\n");
    }
    else if(timeY > timeX)
    {
        printf("Runner 1 wins\n");
    }
    
    /* Remove this part if only one of them wins or input format does not change*/

    else
    {
        printf("Unexpected input, Please enter correct data.\n");
    }
    
    return 0;
}    
float timeTaken(char str[], float dist)
{
    char *p = str;
    static float arr[10];
    int i = 0;
    while (*p)
    {
        if (isdigit(*p))
        {
            float val = strtof(p, &p);
            arr[i++] = val;
        }
        else
        {
                p++;
        }
    }
    //calculate time, replace 'dist' with 400 if it is fixed

    float timeY = (dist - arr[2])/arr[1];
    return timeY;
} 

Recommended reading:

UNIX vs Linux- Why Linux was created?

Output:

Runner 2 wins

Summary:

In this article, we learned how to extract integer and floating point numbers from a string and then we learnt how to implement that in our code.

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at programming-articles.com, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →

Leave a Reply

Your email address will not be published. Required fields are marked *