Open In App

strrev() function in C

The strrev() function is a built-in function in C and is defined in string.h header file. The strrev() function is used to reverse the given string. 

Syntax:



char *strrev(char *str);

Parameter:

Returns: This function doesn’t return anything but the reversed string is stored in the same string.



Note: This is a non-standard function that works only with older versions of Microsoft C. 

Below programs illustrate the strrev() function in C: 

Example 1:- 




// C program to demonstrate
// example of strrev() function
 
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[50] = "geeksforgeeks";
 
    printf("The given string is =%s\n", str);
 
    printf("After reversing string is =%s", strrev(str));
 
    return 0;
}

Output:

The given string is = geeksforgeeks
After reversing string is = skeegrofskeeg

Note: Please note strrev() is non-standard and may not be available.

Example 2:- 




// C program to demonstrate
// example of strrev() function
 
#include <stdio.h>
#include <string.h>
 
int main()
{
    char str[50] = "123456789";
 
    printf("The given string is =%s\n", str);
 
    printf("After reversing string is =%s", strrev(str));
 
    return 0;
}

Output:

The given string is = 123456789
After reversing string is = 987654321

Note: Please note strrev() is non-standard and may not be available.

C Program to Manually Reverse a String

We can create our own strrev() function to reverse a string simply using a loop. The below program demonstrates how to reverse a string in C.




// C Program to reverse a string
#include <stdio.h>
#include <string.h>
 
// function to reverse a string
void strrev(char* str)
{
    // if the string is empty
    if (!str) {
        return;
    }
    // pointer to start and end at the string
    int i = 0;
    int j = strlen(str) - 1;
 
    // reversing string
    while (i < j) {
        char c = str[i];
        str[i] = str[j];
        str[j] = c;
        i++;
        j--;
    }
}
 
// driver code
int main(void)
{
    char a[] = "hello world";
    strrev(a);
    printf("%s", a);
    return 0;
}

Output
dlrow olleh

Time Complexity: O(n)
Space Complexity: O(1)

In the above example, we have used two indexes,


Article Tags :