How to move the digits of a string with digits and letters to the beginning of the string in C

1 Answer

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

#define SIZE 16

void moveDigitsToStart(char *str) {
    int len = strlen(str);
    char digits[SIZE];  // To store digits
    char others[SIZE];  // To store non-digits
    int digitIndex = 0, otherIndex = 0;

    // Separate digits and non-digits
    for (int i = 0; i < len; i++) {
        if (isdigit(str[i])) {
            digits[digitIndex++] = str[i];
        } else {
            others[otherIndex++] = str[i];
        }
    }

    // Null-terminate the strings
    digits[digitIndex] = '\0';
    others[otherIndex] = '\0';

    // Combine digits and non-digits back into the original string
    strcpy(str, digits);
    strcat(str, others);
}

int main() {
    char str[] = "d2c54be3a1";

    moveDigitsToStart(str);

    printf("Modified string: %s\n", str);
    
    return 0;
}


/*
run:

Modified string: 25431dcbea

*/

 



answered May 27, 2025 by avibootz
...