C program to reverse a string

Created with Sketch.

 

C program to reverse a string

C program to reverse a string that a user inputs. If the string is “hello” then, the output is “olleh.” C program to reverse a string using strrev, without using strrev, recursion and pointers. A string which remains the same on reversal is a palindrome.

Reverse a string in C using strrev

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

int main()
{
char s[100];

printf(“Enter a string to reverse\n);
gets(s);

strrev(s);

printf(“Reverse of the string: %s\n, s);

return 0;
}

C reverse string program output:
Reverse string C program output

 

String reversal without strrev function

We find the length of the string without using strlen function and then copy its characters in reverse order (from end to beginning) to a new string using a for loop.

#include <stdio.h>

int main()
{
char s[1000], r[1000];
int begin, end, count = 0;

printf(“Input a string\n);
gets(s);

// Calculating string length

while (s[count] != \0)
count++;

end = count 1;

for (begin = 0; begin < count; begin++) {
r[begin] = s[end];
end–;
}

r[begin] = \0;

printf(“%s\n, r);

return 0;
}

C program to reverse a string using recursion

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

void reverse(char*, int, int);

int main()
{
char a[100];

gets(a);

reverse(a, 0, strlen(a)1);

printf(“%s\n, a);

return 0;
}

void reverse(char *x, int begin, int end)
{
char c;

if (begin >= end)
return;

c          = *(x+begin);
*(x+begin) = *(x+end);
*(x+end)   = c;

reverse(x, ++begin, end);
}

In the recursive method, we swap characters at the beginning and the end of the string and move towards the middle of the string. This method is inefficient due to repeated function calls.

C program to reverse a string using pointers

Now we will invert a string using pointers or without using the library function strrev.

#include<stdio.h>

int string_length(char*);
void reverse(char*);

main()
{
char s[100];

printf(“Enter a string\n);
gets(s);

reverse(s);

printf(“Reverse of the string is \”%s\”.\n, s);

return 0;
}

void reverse(char *s)
{
int length, c;
char *begin, *end, temp;

length = string_length(s);
begin  = s;
end    = s;

for (c = 0; c < length 1; c++)
end++;

for (c = 0; c < length/2; c++)
{
temp   = *end;
*end   = *begin;
*begin = temp;

begin++;
end–;
}
}

int string_length(char *pointer)
{
int c = 0;

while( *(pointer + c) != \0 )
c++;

return c;
}

Leave a Reply

Your email address will not be published. Required fields are marked *