How to Reverse String in C

In this post, I am going to share two ways of reversing a string in C. First one is the easy one. All you need to do is just print the input string from the last index to first index. Here is the example:

#include <stdio.h>
#include <string.h>

int main()
{
    char str[1000];
    int i, length;
    printf("Enter a string: ");
    gets(str);
    length = strlen(str);
    printf("Reversed string: ");
    for(i=length-1; i>=0; i--)
        printf("%c",str[i]);
    return 0;
} 

The second way is actually using some logics. Here I won’t print the string from the last character rather I will reverse the entire character array. That is, the first character will be the last character and the last character will be the first character. I will use a temporary variable namely temp and a nested loop. See how I am doing this:

#include <stdio.h>
#include <string.h>

int main()
{
    char str[1000], temp;
    int i,j, length;
    printf("Enter a string: ");   
    gets(str);
    int length = strlen(str);
    for(i=0;i<length-1;i++){
        for(j=0;j<length-1-i;j++){
            temp = str[j];
            str[j] = str[j+1];
            str[j+1] = temp;
        }
    }
    printf("Reversed String: %s\n",str);
    return 0;
} 

1 comments :

  1. Thanks to you for this nice @ awesome solutions. Very good job.

    ReplyDelete

Spam comments will be deleted. :)

 
Loading...
TOP