Reverse a String In-Place

Code

#include <stdio.h>

void reverse_string(char *str) {
    // Your logic here
    if (str == NULL || *str == '\0') return;
    char *start = str;
    char *end = str;
    // Đưa con trỏ end đến ký tự cuối cùng (trước \0)
    while (*(end + 1) != '\0')
    {
        end++;
    }
    // Hoán đổi cho đến khi hai con trỏ gặp nhau
    while (start < end)
    {
        char temp = *start;
        *start = *end;
        *end = temp;
        start++;
        end--;
    }

    // int len = 0;
    // while(*(str + len) != '\0')
    // {
    //     len++;
    // }
    // for(int i = 0; i < len/2; i++)
    // {
    //     char temp = *(str+ i);
    //     *(str+ i) = *(str + len-1 - i);
    //     *(str + len-1 - i) = 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