93. Reverse a String In-Place

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

void reverse_string(char *str) {
    // Your logic here
    // While loop
    // Go from ends, put into temp place and swap until middle
    int length=0;
    int i=0;
    //1. Get string length
    while(str[length] != '\0'){
        length++;
    }
    //printf("StrLen: %d\n", length);
    
    //2. Swap values
    while(i<(length/2)){
        char temp = str[i]; //Copy first char into temp
        str[i] = str[length-i-1]; //Copy last char into first
        str[length-i-1] = temp; //Copy temp into last char
        i++;
    }
}

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

 

 

 

Was this helpful?
Upvote
Downvote