How to extract all digits from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h>   // for isdigit()
#include <string.h>  // for strlen()

/*
    extract_digits
    --------------
    Scans a string and copies every digit ('0'–'9') into an output buffer.

    Parameters:
        src  - input string to scan
        dest - output buffer to store extracted digits

    Notes:
        - The caller must ensure 'dest' is large enough.
        - The function writes a null terminator at the end.
*/
void extract_digits(const char *src, char *dest) {
    size_t write_index = 0;

    // Walk through each character in the string
    for (size_t i = 0; src[i] != '\0'; i++) {

        // Use the standard library's classification function
        // to check whether the current character is a digit.
        if (isdigit((unsigned char)src[i])) {
            dest[write_index++] = src[i];
        }
    }

    // Properly terminate the resulting string
    dest[write_index] = '\0';
}

int main(void) {
    const char *str = "5 ruby8go 9001 c c++ 17python";

    // Allocate a buffer large enough to hold all digits.
    // Worst case: every character is a digit.
    char digits[strlen(str) + 1];

    // Extract digits from the input string
    extract_digits(str, digits);

    // Display the result
    printf("Original: %s\n", str);
    printf("Digits:   %s\n", digits);

    return 0;
}


/*
run:

Original: 5 ruby8go 9001 c c++ 17python
Digits:   58900117

*/

 



answered Sep 16 by avibootz
...