C Program to Reverse a String Without using Strrev

We require a string in the reverse format in a number of situations, such as when looking for palindromes. There are various ways to reverse a string, but strrev is the simplest ().

What is strrev Function in C?

One of the built-in functions for handling strings is strrev(), which is already defined in the C header file string.h. When reversing a string, it is utilized.

Syntax: strrev(char *string);

The syntax above returns a string in reverse to the same string variable.

Also Read: How to convert string to uppercase without using Strupr in C

C Program to Reverse a String using Strrev

#include <stdio.h>

include <string.h>

//header file for basic i/o program and string handling function respectively

int main()
//starting point for program execution
{
char str[10] = “Hello”;
//declaration of str

strrev(str);

//string handling function strrev to reverse the string and store it back in the str variable

printf(“Reversed string: %s”, str);

//print reversed string

return 0;

}

Output: olleH

C Program to Reverse a String Without using Strrev

Strrev() fails with the error “Undefined reference to strrev” when using the C-GCC compiler since it is not supported in this context. A special piece of code must be developed in this compiler to reverse a string.

C Program to Reverse a String in C Without Strrev using for loop

#include <stdio.h>

#include <string.h>

//header file for basic i/o program and string handling function respectively

int main()
//starting point for program execution

{
char str1[10] = “Hello”, reversed[30];
//define string variables to store original and reversed string

int i;
//define int type variable i to track string index

int length = strlen(str1);
//accessing length of the str1 variable using strlen()

for(i=0; i<length; ++i)
//for loop to reverse the string using the index value

{

reversed[length-i-1] = str1[i];

//assign str1 character to reversed variable in backward

}
printf(“First string %s\n”,str1);
printf(“Reversed string %s\n”, reversed);
//print the original and reverse string

return 0;
}

Output: olleH

Using While Loop

#include <stdio.h>

#include <string.h>

//header file for basic i/o program and string handling function respectively

int main()
//starting point for program execution

{
char str[10] = “Hello”;
char temp;
Int i=0, j=0;
j = strlen() – 1;
//initializing variables

while(i<j){
//loop to check if i is less than j

temp = str[j];
str[j] = str[i];
str[i] = temp;
//exchanging characters

i++; //increasing i
j – -; //decreasing j
}
printf(“The reversed string: %s”,);
return 0;
}

Output: olleH

As opposed to the ANSI C compiler, which has it.

Greetings, My name is Rumi Sadaf. I work as both a content writer and a programmer. In essence, I explain what I know and aid others in understanding programming concepts. Happy Viewing.

Leave a Comment