Computer Science

Reverse Strings in C

Reverse

There are three ways to reverse string in c.They are as follows:

  1. Use predefined function from c library to reverse a string.
  2. Directly print reversed string.
  3. 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<stdio.h>
#include<string.h> //header file that contain strrev() function
int main()
{
char str[20];
printf(“Enter String to be reversed\n”);
gets(str);
printf(“String is %s\n”,str);
printf(“Reverse String is %d\n”,strrev(str));
return 0;
}

2. Printing Reversed String

We can directly print a string in reversed order.

#include<stdio.h>
#include<string.h>
int main()
{
char str[20];
int i,length;
printf(“Enter a string\n”);
gets(str);
length=strlen(str); //Count the length of string
for(i=length-1;i>=0;i–)
{
printf(“Reversed string is %c”,str[i]);
}
return 0;
}



3. Write own code of reversing string

#include<stdio.h>
#include<conio.h>
int main()
{
char a[20],b[20];
int count=0,i=0,j=1;
printf(“Enter a string to be reversed\n”);
scanf(“%s”,&a);
while(a[count]!=’\0′) /*Calculate length of string*/
{
count++;
}
j=count-1;
while(i<count) /* Reverses string*/
{
b[i]=a[j];
j–;
i++;
}
b[i]=’\0′; /*Terminates string*/
printf(“%s\n”,b);
return 0;
}

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..!!

 

Myself Shubham an computer science engineer with lots of dream having an unseen attitude with lots of thoughts

Tagged , , , ,

About Shubham Lashkan

Myself Shubham an computer science engineer with lots of dream having an unseen attitude with lots of thoughts
View all posts by Shubham Lashkan →

Leave a Reply