C Reverse String: strrev()

In the C programming language, reversing a string can be done using the strrev() function. The strrev() function is a part of the string.h library and is used to reverse a given string.

To use the strrev() function, you need to include the string.h header file in your program. This can be done by adding the following line at the beginning of your code:

#include <string.h>

Once you have included the string.h header file, you can use the strrev() function to reverse a string. The syntax of the strrev() function is as follows:

char *strrev(char *str);

The strrev() function takes a string as an argument and returns a pointer to the reversed string. It modifies the original string in place, so there is no need to assign the result to a new variable.

Here is an example that demonstrates how to use the strrev() function to reverse a string:

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

int main() {
    char str[] = "Hello, World!";
    
    printf("Original string: %sn", str);
    
    // Reverse the string
    strrev(str);
    
    printf("Reversed string: %sn", str);
    
    return 0;
}

Output:

Original string: Hello, World!
Reversed string: !dlroW ,olleH

In this example, we first declare a character array str and initialize it with the string “Hello, World!”. We then use the printf() function to display the original string. Next, we call the strrev() function to reverse the string. Finally, we use the printf() function again to display the reversed string.

It is important to note that the strrev() function works only with null-terminated strings. If the input string is not null-terminated, the behavior of the function is undefined. Therefore, make sure that the string you pass to the strrev() function is properly null-terminated.

Additionally, it is worth mentioning that the strrev() function is not a standard C function and is not available in all C compilers. If you encounter an error or warning related to the strrev() function, it is possible that your compiler does not support it. In such cases, you can implement your own string reversal function using a loop or recursion.

Overall, the strrev() function is a convenient way to reverse a string in C. It allows you to quickly and easily reverse the characters in a string without having to write complex code. Just remember to include the string.h header file and ensure that your string is null-terminated before using the strrev() function.

Scroll to Top