đ Reverse a String in C Using strrev()
and Without Function
In this tutorial, you’ll learn how to reverse a string using the built-in strrev()
function and also manually without using any function. Let's explore both methods.
✅ Method 1: Using strrev()
Function
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
gets(str); // Use fgets() in modern C
strrev(str); // Built-in function (Turbo C)
printf("Reversed string: %s\n", str);
return 0;
}
đ§ Explanation:
strrev()
reverses the string in-place.gets()
is used here for simplicity, but is unsafe. Preferfgets()
in modern compilers.
đ ️ Method 2: Without Using Any Function
#include <stdio.h>
#include <string.h>
int main() {
char str[100], temp;
int start = 0, end;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
end = strlen(str) - 1;
// Remove newline if present
if (str[end] == '\n') {
str[end] = '\0';
end--;
}
while (start < end) {
temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
printf("Reversed string: %s\n", str);
return 0;
}
đ§ Explanation:
- This method uses index-based character swapping to reverse the string manually.
- Works in any standard C compiler (no external functions used).
đ Summary
strrev() is useful in compilers that support it (like Turbo C), but writing your own reverse logic ensures compatibility across all platforms. It's also a great exercise in learning character arrays and loops!
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ