C Program: Reverse a String
A reversed string has its characters re-ordered from the original string, starting from the last to the first. If the input string is "hello", the program should reverse it and print out "olleh".
For some versions of C, there already exist a built-in function called strrev()
for the purpose, available under the <string.h>
header library. The input string needs to be passed as an argument to it; which then reverses it.
The below program illustrates the use of the strrev()
function to reverse a given string. Note the use of %[^\n]
inside the scanf()
function for reading the string. The difference is, with %s
, the reading goes off with the encounter of first space/blank character, while %[^\n]
accepts the spaces.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
scanf("%[^\n]", str);
strrev(str);
printf("The reverse of the entered string is %s \n", str);
return 0;
}
The strrev()
function, however, is not available for some versions of C, like the C99.
Reversing a String Without strrev()
We can achieve the same without using the strrev()
function. In the below program, two variables of type char
— str[]
& revstr[]
— are declared to hold the input string and the reversed string respectively. The end
variable counts the number of characters of the given string, but is decremented with each character assignment inside the second while
loop.
#include <stdio.h>
int main() {
char str[100], revstr[100];
unsigned short start = 0, end = 0;
printf("Enter a string: ");
scanf("%[^\n]", str);
// count the number of characters
while (str[end] != '\0')
end++;
// backward assignment, starting from the last character
while (end > 0) {
revstr[start] = str[end-1];
end--;
start++;
}
revstr[start] = '\0';
printf("The reversed string is: %s", revstr);
return 0;
}