Summary: In this example, we will learn different ways to reverse a string in the C programming language.

Example:

If the user enters ‘Pencil‘, then the output should be ‘licneP‘.

Method 1: Using Loop

The idea is to assign characters of the input string to its reverse in reverse order using the ‘while’ or ‘for’ loop.

Output:

Reverse a string in C

Using this method, we can also reverse a string with whitespace i.e., a whole sentence.

Method 2: Using Recursion

We can also reverse a string in C using the recursion algorithm.

We extract an character from the string on each recursive call and reassign them in reverse order during the traceback of the recursive calls.

Output:

Enter a string
adarsh
hsrada


Method 3: Using strrev()

string.h library has an inbuilt function called strrev() which in-place reverses the string passed as an argument.

Note: strrev() only works with non-linux compiler. strrev() method is not present in glibc compiler.

Output:

C Program to reverse a String

These are three different ways we can use to reverse a string in a C programming language. Please comment below if you know any other methods.

Leave a Reply

twenty − 14 =