Reverse of a string

Theory

In C programming, a string is a sequence of characters terminated with a null character \0.

How to declare a string?

Here's how you can declare strings:
char s[5];

Here, we have declared a string of 5 characters.

How to initialize strings?

You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

Reverse a String in C

Reversing a string is the technique that reverses or changes the order of a given string so that the last character of the string becomes the first character of the string and so on. Furthermore, we can also check the Palindrome of the given string by reversing the original string.

For example, we enter a string "APPLE", and then use the reverse algorithm. The reverse algorithm returns the string "ELPPA" which is completely reverse of the original string.

Print the reverse of a string using strrev() function

Let's consider an example to print the reverse of a string using the strrev() function.

#include <stdio.h>

#include <string.h>

int main()

{

char str[40]; // declare the size of character string

printf (" \n Enter a string to be reversed: ");

scanf ("%s", str);

// use strrev() function to reverse a string

printf (" \n After the reverse of a string: %s ", strrev(str));

return 0;

}

Output

Enter a string to be reversed: AMBULANCE

After the reverse of a string: ECNALUBMA