Strings · beginner
C Program to Reverse a String
Reverse a string in place in C by swapping characters from both ends, write it as a reusable function, and print a string backwards with a loop.
- char arrays
- strlen()
- swapping
- in-place algorithms
C has no built-in string reverse in the standard library (strrev is a non-standard extension). Reversing in place means swapping the first and last characters, then the second and second-to-last, until the middle.
The string must be a modifiable array (char text[] = "…"), not a pointer to a string literal, which may live in read-only memory.
The program
#include <stdio.h>
#include <string.h>
void reverse(char *s) {
size_t n = strlen(s);
for (size_t i = 0; i < n / 2; i++) {
char temp = s[i];
s[i] = s[n - 1 - i];
s[n - 1 - i] = temp;
}
}
int main(void) {
char text[] = "Hello, World";
reverse(text);
printf("%s\n", text);
char word[] = "C";
reverse(word);
printf("%s\n", word);
return 0;
}dlroW ,olleH
CHow it works
- strlen(s) counts the characters before the terminating '\0'.
- The loop runs to the middle (n / 2 swaps); for an odd length the middle character stays where it is.
- Each pass swaps s[i] with its mirror s[n - 1 - i] using a temporary char.
- The '\0' terminator is not moved, so the reversed text is still a valid string.
Another way: Print backwards without changing the string
If you only need to show the reversed text, walk from the last character to the first and print each one.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "stressed";
for (size_t i = strlen(text); i > 0; i--)
putchar(text[i - 1]);
putchar('\n');
return 0;
}dessertsCommon mistakes
- Looping to n instead of n / 2, which swaps every pair twice and leaves the string unchanged.
- Reversing a string literal through char *p = "text": writing to it is undefined behaviour and often crashes.
- Writing for (size_t i = strlen(s) - 1; i >= 0; i--): size_t is unsigned, so i >= 0 is always true and the loop never ends.
Try it yourself
- Reverse the order of words in a sentence: reverse the whole string, then each word.
- Write a recursive version that swaps the ends and recurses on the middle.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.