Ad Code

Responsive Advertisement

strrev() function in C ? With Example

 

Reverse String: strrev() in C


The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev() function.
c
#include <stdio.h> #
include <string.h> 
void reverseString(char *str)
int length = strlen(str); 
int i, j; 
for (i = 0, j = length - 1; i < j; ++i, --j) { 
// Swap characters at positions i and j
char temp = str[i];
 str[i] = str[j]; 
 str[j] = temp; } 
int main()
char myString[] = "Hello, World!"
// Print the original string 
printf("Original String: %s\n", myString); 
// Reverse the string 
 reverseString(myString); 
// Print the reversed string 
printf("Reversed String: %s\n", myString);
return 0;
 }


In this example, the reverseString function takes a character array (char*) as an argument and reverses the order of characters in the array. The main function demonstrates how to use this function.

Keep in mind that this implementation modifies the original string in place. If you need to preserve the original string, consider creating a copy and then reversing it. Additionally, be cautious about null-terminated strings and ensure that you have enough space in the array to store the reversed string.

Note: If you are working with C++, the std::reverse function from the <algorithm> header can be used to reverse a string. If you are working with C and want a more convenient string manipulation library, you might consider using a library like libstring or other similar third-party libraries that provide additional string manipulation functions.

Post a Comment

0 Comments