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:
- 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
// C program to demonstrate // example of strrev() function #include <stdio.h> #include <string.h> int main() { char str[50] = "w3wiki" ; printf ( "The given string is =%s\n" , str); printf ( "After reversing string is =%s" , strrev(str)); return 0; } |
Output:
The given string is = w3wiki After reversing string is = skeegrofskeeg
Note: Please note strrev() is non-standard and may not be available.
Example 2:-
C
// 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
// 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; } |
dlrow olleh
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.
Contact Us