Reverse Strings in C: Complete Guide
In C language, the reverse function can be used by following these steps:
- Include the header file
. - Create a character array to store the string to be reversed.
- Read input from the user using either the gets() or scanf() function and store it in a defined character array.
- Use the strrev() function, which is used to reverse a string. The declaration of this function can be found in the
header file. - Print the reversed string.
Here is a sample program demonstrating how to use the inverse function:
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
strrev(str);
printf("Reversed string: %s\n", str);
return 0;
}
In this example, the gets() function is used to read a string from user input and store it in the str array. Then, the strrev() function is used to reverse the string. Finally, the reversed string is printed.
It’s important to note that the strrev() function may not be available in some compilers because it is not a standard C function. If your compiler does not support the strrev() function, you can implement a reverse function yourself. Here is an example of a simple custom reverse function:
#include <stdio.h>
#include <string.h>
void reverse(char str[]) {
int i, j;
char temp;
for (i = 0, j = strlen(str) - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
reverse(str);
printf("Reversed string: %s\n", str);
return 0;
}
In this example, the reverse() function is used to reverse a string. The function starts with two pointers at the ends of the string, gradually swapping characters until the pointers meet. Afterwards, the reversed string is printed.
Please be cautious when using the gets() function as it may result in a buffer overflow. A better option is to use the fgets() function to read strings and then remove the newline character after reading.