Reverse a String In-Place

Code

#include <stdio.h>
int sl(char *x){
    int c=0;
    while(*x++){
    c++;}
    return c;
}
void reverse_string(char *str) {
int n = sl(str);
char *last = str+(n-1);
while(str<last){
   char t=*str;
    *str=*last;
    *last=t;
    str++;
    last--;
}
}

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    int i = 0;
    while (str[i] != '\0') {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    reverse_string(str);
    printf("%s", str);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

firmware

Expected Output

erawmrif