There are three ways to reverse string in c.They are as follows:
- Use predefined function from c library to reverse a string.
- Directly print reversed string.
- Write own code of reversing a string permanently by swapping.
Let’s see all the program to reverse a given string.
1. Predefined Function
C library has a predefined function called as strrev() that reverses a string. It takes only one argument that is the variable which holds the string to be reversed or the string itself direclty surrounded by double qoutes. Lets have a look at the program.
#include<string.h> //header file that contain strrev() function
printf(“Enter String to be reversed\n”);
printf(“String is %s\n”,str);
printf(“Reverse String is %d\n”,strrev(str));
2. Printing Reversed String
We can directly print a string in reversed order.
printf(“Enter a string\n”);
length=strlen(str); //Count the length of string
printf(“Reversed string is %c”,str[i]);
3. Write own code of reversing string
printf(“Enter a string to be reversed\n”);
while(a[count]!=’\0′) /*Calculate length of string*/
while(i<count) /* Reverses string*/
b[i]=’\0′; /*Terminates string*/
Here we would have used strlen() function direclty to count the length of string but here we are reversing string explicitly that’s why we don’t used predefined function strlen to count length of string and counted it too explicitly.
Above all code snippets are for reversing a string if you have any new method then feel free to share and if you found something wrong in above code then let us know in the comment box below.
For study materials of GATE Click Here..!!
For more on computer Science Click Here..!!