Reverse a String in C

Many old books use strrev() to reverse a string. But this function is not part of standard C. It works in some Windows compilers only, and gives an error in GCC and Clang. So we write our own function, which works everywhere.

Method 1: print in reverse order

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

int main(void) {
    char s[] = "Hello";

    for (int i = strlen(s) - 1; i >= 0; i--) {
        printf("%c", s[i]);
    }
    printf("\n");
    return 0;
}

Output:

Output of the above program is

olleH

Method 2: reverse the string itself

We swap the first and last characters, then the second and second last, and so on until we reach the middle.

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

void reverse(char s[]) {
    int left = 0, right = strlen(s) - 1;

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

int main(void) {
    char word[] = "Programming";

    reverse(word);
    printf("%s\n", word);
    return 0;
}

Output:

Output of the above program is

gnimmargorP

Palindrome check

A palindrome reads the same from both sides, like “madam”.

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

int main(void) {
    char s[] = "madam";
    int n = strlen(s), isPal = 1;

    for (int i = 0; i < n / 2; i++) {
        if (s[i] != s[n - 1 - i]) {
            isPal = 0;
            break;
        }
    }
    printf(isPal ? "Palindrome\n" : "Not a palindrome\n");
    return 0;
}

Output:

Output of the above program is

Palindrome

Note: The string must be a char array (char s[]) to change it. A string literal pointer (char *s = "Hello") is read only.

Next: C Convert String to Lowercase and Uppercase.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?