strrev() and Portable String Reversal in C

strrev() is a commonly seen compiler extension for reversing a string, but it is not part of the ISO C standard library. Portable C code should reverse the characters directly or use a small helper function.

Portability: do not assume strrev() is available on GCC, Clang or every C implementation.

Legacy Syntax Top ↑

strrev(string);  // non-standard extension

Portable String-Reversal Function Top ↑

#include <stdio.h>
#include <string.h>

void reverse_string(char text[]) {
    size_t left = 0;
    size_t right = strlen(text);

    if (right == 0) {
        return;
    }

    right--;

    while (left < right) {
        char temp = text[left];
        text[left] = text[right];
        text[right] = temp;
        left++;
        right--;
    }
}

int main(void) {
    char text[] = "plus2net";

    reverse_string(text);
    printf("%s\n", text);

    return 0;
}

Output

ten2sulp

Reverse User Input Top ↑

#include <stdio.h>
#include <string.h>

void reverse_string(char text[]) {
    size_t left = 0;
    size_t right = strlen(text);

    if (right == 0) {
        return;
    }

    right--;

    while (left < right) {
        char temp = text[left];
        text[left] = text[right];
        text[right] = temp;
        left++;
        right--;
    }
}

int main(void) {
    char text[80];

    printf("Enter a string: ");
    if (fgets(text, sizeof text, stdin) == NULL) {
        return 1;
    }

    text[strcspn(text, "\n")] = '\0';
    reverse_string(text);

    printf("Reversed: %s\n", text);
    return 0;
}

Reverse Several Strings Top ↑

#include <stdio.h>
#include <string.h>

void reverse_string(char text[]) {
    size_t left = 0;
    size_t right = strlen(text);

    if (right == 0) {
        return;
    }

    right--;

    while (left < right) {
        char temp = text[left];
        text[left] = text[right];
        text[right] = temp;
        left++;
        right--;
    }
}

int main(void) {
    char words[][20] = {"plus2net", "hello", "world"};

    for (size_t i = 0; i < 3; i++) {
        reverse_string(words[i]);
        printf("%s\n", words[i]);
    }

    return 0;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer