String Reversal without using indexing.

Jaks_maths 0 Tallied Votes 139 Views Share

Used recursion to reverse the string. Another method for string reversal.

#include<stdio.h>
#include<string.h>
char *strrev(char *str)
{
char s[2],*t;
if(strlen(str)==1)
return &str[0];
else
{
s[0]=str[0];
s[1]='\0';
t=strrev((str+1));
strcat(t,s);
return t;
}
}
main()
{
char *str,*dstr;
printf("\n Enter Input string ");
gets(str);
dstr="";
dstr=strrev(str);
printf(" Reverse String %s",dstr);
}
~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

The above method for gettign the string from the user wont work and would give an run time error since the user input is stored in a character ptr for whom no memory has been allocated.

Better use

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

char *strrev(char *str)
{
  char s[2],*t;
  if(strlen(str)==1)
    return &str[0];
  else
  {
    s[0]=str[0];
    s[1]='[B]\0[/B]';
    t=strrev((str+1));
    strcat(t,s);
    return t;
   }
}


int main (void)
{
  char str[BUFSIZ];
  char* dstr;
  printf("[B]\n[/B] Enter Input string ");
  fgets(str, BUFSIZ, stdin);
  dstr="";
  dstr=strrev(str);
  printf(" Reverse String %s",dstr);
}
risby 0 Newbie Poster

Untested, unformatted, uses deprecated functions like gets and doesn't allocate space for its data. Should be removed.

~s.o.s~ 2,560 Failure as a human Team Colleague Featured Poster

Thats the reason i posted the updated version which works and uses safe functions like fgets().
:mrgreen:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.