C program to reverse string

In this guide we will learn how to reverse string in C. We will take a string as input and then reverse it by library function, without library function, recursion or pointers.

Assume the user gives the string ‘programming‘, then we will make it ‘gnimmargorp‘ by our written C program. Let’s see the easiest solution to this.

Reverse string using strrev() library function

strrev() is a library function defined inside the string.h header file which can reverse the given string. We must have to include the header file when working string function like strrev().

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

int main(){
   char main_string[200];

   printf("Enter a string here to reverse it : \n");
   gets(main_string);

   strrev(main_string);

   printf("\nString after reversal is : \n%s\n", main_string);

   return 0;
}

Output of reverse string program:

reverse-string-program-in-c-c-string-reversal-program

String reverse program without strrev()

// reverse string program without library function

#include <stdio.h>
int main(){
   char main_string[100], rev_string[100];
   int counter = 0, start, finish;

   printf("Input any string to reverse it : \n");
   gets(main_string);

   while(main_string[counter] != '\0'){
      counter++;
   }

   finish = counter - 1;

   for(start = 0; start < counter; start++){
      rev_string[start] = main_string[finish];
      finish--;
   }

   rev_string[start] = '\0';

   printf("\nReverse string is : \n%s\n", rev_string);

   return 0;
}

Output of program:

Input any string to reverse it :
string reversal by CP

Reverse string is :
PC yb lasrever gnirts

You can also use function to reverse a string. Try this using function in your own.

Reverse string using pointer in C

// reverse string program using pointer

#include<stdio.h>

int len_finder(char *p){   // find string length by function
    int i = 0;

    while(*(p + i) != '\0'){
        i++;
    }
    return i;
}

void str_rev_funct(char *strg){   // string reverse function
    int strln, k;
    char *s, *e, t;

    strln = len_finder(strg);
    s = strg;
    e = strg;

    for (k = 0; k < strln - 1; k++){
      e++;
    }

    for (k = 0; k < strln / 2; k++){
       t = *e;
       *e = *s;
       *s = t;

       s++;
       e--;
    }
}

int main(){
    char main_string[200];

    printf("Enter your main string to reverse it : \n");
    gets(main_string);

    str_rev_funct(main_string);

    printf("\nYour string after reversing is : \n%s\n", main_string);

    return 0;
}

Reverse string program output:

Enter your main string to reverse it :
reverse string program

Your string after reversing is :
margorp gnirts esrever

Previous pagePrint string

Next pageDelete vowels