strrev() is a commonly seen compiler extension for reversing a string, but it is not part of the ISO C standard library. Portable C code should reverse the characters directly or use a small helper function.
strrev() is available on GCC, Clang or every C implementation.strrev(string); // non-standard extension
#include <stdio.h>
#include <string.h>
void reverse_string(char text[]) {
size_t left = 0;
size_t right = strlen(text);
if (right == 0) {
return;
}
right--;
while (left < right) {
char temp = text[left];
text[left] = text[right];
text[right] = temp;
left++;
right--;
}
}
int main(void) {
char text[] = "plus2net";
reverse_string(text);
printf("%s\n", text);
return 0;
}
Output
ten2sulp
#include <stdio.h>
#include <string.h>
void reverse_string(char text[]) {
size_t left = 0;
size_t right = strlen(text);
if (right == 0) {
return;
}
right--;
while (left < right) {
char temp = text[left];
text[left] = text[right];
text[right] = temp;
left++;
right--;
}
}
int main(void) {
char text[80];
printf("Enter a string: ");
if (fgets(text, sizeof text, stdin) == NULL) {
return 1;
}
text[strcspn(text, "\n")] = '\0';
reverse_string(text);
printf("Reversed: %s\n", text);
return 0;
}
#include <stdio.h>
#include <string.h>
void reverse_string(char text[]) {
size_t left = 0;
size_t right = strlen(text);
if (right == 0) {
return;
}
right--;
while (left < right) {
char temp = text[left];
text[left] = text[right];
text[right] = temp;
left++;
right--;
}
}
int main(void) {
char words[][20] = {"plus2net", "hello", "world"};
for (size_t i = 0; i < 3; i++) {
reverse_string(words[i]);
printf("%s\n", words[i]);
}
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.