How to reverse a string without affecting special characters in C

1 Answer

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

void swap(char* a, char* b) {
    char tmp;

    tmp = *a;
    *a = *b;
    *b = tmp;
}

void reverseStringWithoutTheSpecialCharacters(char str[]) {
    size_t right = strlen(str) - 1, left = 0;

    while (left < right) {
        if (!isalpha(str[left]))
            left++;
        else if (!isalpha(str[right]))
            right--;
        else {
            swap(&str[left], &str[right]);
            left++;
            right--;
        }
    }
}
int main()
{
    char str[] = "ab*#cde!@$,fg{}";

    reverseStringWithoutTheSpecialCharacters(str);

    puts(str);
}




/*
run:

gf*#edc!@$,ba{}

*/

 



answered Aug 22, 2022 by avibootz
edited Aug 23, 2022 by avibootz
...