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:
- str: The given string which is needed to be reversed.
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
#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
#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
#include <stdio.h>
#include <string.h>
void strrev( char * str)
{
if (!str) {
return ;
}
int i = 0;
int j = strlen (str) - 1;
while (i < j) {
char c = str[i];
str[i] = str[j];
str[j] = c;
i++;
j--;
}
}
int main( void )
{
char a[] = "hello world" ;
strrev(a);
printf ( "%s" , a);
return 0;
}
|
Time Complexity: O(n)
Space Complexity: O(1)
In the above example, we have used two indexes,
- i = 0, pointing to the start of the string.
- j = strlen(str) – 1, pointing to the last character of the string (before the null character).
- We then increment i and decrement j while replacing the characters at both indexes.
- We keep doing that till i < j.