C strrev() Function
The strrev()
function in C is used to reverse a string. It is not a standard function in the C library, but it can be implemented easily. The function reverses the characters in a string in-place.
Syntax of strrev()
The syntax of the strrev()
function is as follows:
Syntax:
char *strrev(char *str);
The function takes one argument:
- str: A pointer to the string that will be reversed. The string is reversed in-place, meaning the original string is modified.
The function returns a pointer to the reversed string.
Example of strrev() Function
Here is an example that demonstrates how the strrev()
function works. Since strrev()
is not a part of the standard C library, we will implement it manually.
Example:
#include <stdio.h>>
#include <string.h>>
// Function to reverse a string
char* strrev(char* str) {
int len = strlen(str);
int i, j;
char temp;
// Reversing the string
for (i = 0, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
return str;
}
int main()
{
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
// Reversing the string
strrev(str);
printf("Reversed String: %s\n", str);
return 0;
}
Output:
Original String: Hello, World!
Reversed String: !dlroW ,olleH
Reversed String: !dlroW ,olleH
Explanation of the Example
In this example:
- The function
strrev()
is implemented manually to reverse the input string. - We initialize two variables,
i
andj
, to point to the beginning and end of the string, respectively. - In a loop, characters at positions
i
andj
are swapped untili
is greater than or equal toj
. - The reversed string is then printed.
Important Notes
- The
strrev()
function is not part of the C standard library, so you need to implement it yourself or use a third-party library that includes it. - The function reverses the string in-place, which means it modifies the original string. There is no need to allocate additional memory for the reversed string.
- Make sure the string is null-terminated before passing it to the function. Otherwise, it may lead to undefined behavior.