Reverse a String In-Place

Code

#include <stdio.h>

int str_len(char *str){
    int count =0;
    for (size_t i=0; i<255; i++){
        if (*(str+i) == '\0'){
            return count;
        }
        count++;
    }
    return -1;
}

void reverse_string(char *str) {
    // Your logic here
    int n = str_len(str);
    for (size_t i=0; i<(n)/2; i++){
        char temp = *(str+i);
        int swp_pos = (n-1)-i;
        *(str+i) = *(str + swp_pos);
        *(str + swp_pos) = temp;
    }
}

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