Program to reverse a String
In this tutorial, we will learn about how to reverse a given String. If the string is "hello"
then, the output should be "olleh"
. We can use this concept to check the palindrome. Because the palindrome string will have the same value even after we reverse it.
It is advised to go through these topics if you are not familiar with C programs.
Mainly there are three ways to reserve a given string:
-
By using the new character array.
-
By swapping the characters of the string.
-
By using standard library functions.
Reverse a String by using the new character array:
Here in this example, firstly we take an input from the user, after taking an input we have to calculate the length of the string. To calculate the length we run a loop from the starting of the character array till a null character found ('\0'
) and in each iteration, we increase the count variable. We assign one less than it to the j because the array starts from zero. After this, we simply copy the characters from the ending one by one from the original character array to a new character array.
#include <stdio.h>
int main()
{
char str[1000], rev[1000];
int i, j, count = 0;
scanf("%s", str);
printf("\nString Before Reverse: %s", str);
//finding the length of the string
while (str[count] != '\0')
{
count++;
}
j = count - 1;
//reversing the string by swapping
for (i = 0; i < count; i++)
{
rev[i] = str[j];
j--;
}
printf("\nString After Reverse: %s", rev);
}
Hello
String Before Reverse: Hello
String After Reverse: olleH
Reverse a String by swapping the characters of the string
This example will sort strings by swapping the characters.
#include <stdio.h>
#include <string.h>
void reverseStr(char str[])
{
int n = strlen(str);
for (int i = 0; i < n / 2; i++)
{
char ch = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = ch;
}
}
int main()
{
char str[1000];
scanf("%s", str);
printf("\nString Before Reverse: %s", str);
reverseStr(str);
printf("\nString After Reverse: %s", str);
return 0;
}
Hello
String Before Reverse: Hello
String After Reverse: olleH
Suggested Tutorials: