How to reverse only the alphabetic characters in a string, keeping other characters in place with C

1 Answer

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

void reverse_only_alphabetic_characters(char *s) {
    int i = 0;
    int j = strlen(s) - 1;

    while (i < j) {
        if (!isalpha((unsigned char)s[i])) {
            i++;
        } else if (!isalpha((unsigned char)s[j])) {
            j--;
        } else {
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;
            i++;
            j--;
        }
    }
}

int main(void) {
    char s[] = "a1-bC2-dEf3-ghIj";

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

    return 0;
}

    
     
/*
run:
     
a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba
    
*/

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...