How to move all special characters to the beginning of a string in C

1 Answer

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

void move_special_characters_to_beginning(const char *s, char *result) {
    char specials[1024] = {0};  // buffer for special characters
    char chars[1024] = {0};     // buffer for alphanumeric + spaces
    int si = 0, ci = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        char ch = s[i];
        if (isalnum((unsigned char)ch) || ch == ' ') {
            chars[ci++] = ch;
        } else {
            specials[si++] = ch;
        }
    }

    // Concatenate specials + chars into result
    strcpy(result, specials);
    strcat(result, chars);
}

int main(void) {
    const char s[] = "c++14$c&^java*(rust) php <>/python 3.14.2";
    char result[2048];  // big enough buffer

    move_special_characters_to_beginning(s, result);

    printf("%s\n", result);

    return 0;
}



/*
run:

++$&^*()<>/..c14cjavarust php python 3142

*/

 



answered Dec 12, 2025 by avibootz

Related questions

...