Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is strrev() Function in C language?
In C programming, the strrev() function is used to reverse a string in-place. However, strrev() is not part of the standard C library ? it is a Microsoft-specific extension found in some compilers. For portable code, we need to implement string reversal manually.
Syntax
char* strrev(char* str);
Where str is the string to be reversed. The function returns a pointer to the reversed string.
Example 1: Manual String Reversal Using Two Pointers
Since strrev() is not standard, here's how to reverse a string using a custom function −
#include <stdio.h>
#include <string.h>
void reverseString(char str[]) {
int start = 0;
int end = strlen(str) - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
char string[50];
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
/* Remove newline if present */
string[strcspn(string, "<br>")] = '\0';
printf("Original string: %s<br>", string);
reverseString(string);
printf("Reversed string: %s<br>", string);
return 0;
}
Enter a string: Hello World Original string: Hello World Reversed string: dlroW olleH
Example 2: Using Recursion
Here's another approach using recursive function to reverse a string −
#include <stdio.h>
#include <string.h>
void reverseRecursive(char str[], int start, int end) {
if (start >= end) {
return;
}
char temp = str[start];
str[start] = str[end];
str[end] = temp;
reverseRecursive(str, start + 1, end - 1);
}
int main() {
char text[] = "TutorialsPoint";
printf("Before reversal: %s<br>", text);
reverseRecursive(text, 0, strlen(text) - 1);
printf("After reversal: %s<br>", text);
return 0;
}
Before reversal: TutorialsPoint After reversal: tnioPslairotpuT
Key Points
-
Portability:
strrev()is not part of standard C, so manual implementation is recommended. - In-place Operation: String reversal modifies the original string without using extra memory.
- Null Terminator: Always ensure the string is properly null-terminated.
- Use
fgets()instead of deprecatedgets()for safe string input.
Conclusion
While strrev() exists in some compilers, implementing manual string reversal ensures code portability. The two-pointer approach is efficient with O(n/2) time complexity and O(1) space complexity.
