简体   繁体   中英

Reversing a string in c with recursion

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the main() function.

#include<stdio.h>

main()
{
  char a[17]="abcdefg";
  reverse(a);
  printf("\n");
  system("PAUSE");
}
int reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
   }
   printf("%c",*a);
}         

it prints the reversed string but I want the reversed string in main() . How can I do this?

Following is one way to reverse string using recursion!

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

void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
    if( iStart < iLast )
    {
        //swap
        char temp = arr[iStart];
        arr[iStart] = arr[iLast];
        arr[iLast] = temp;

        rev_str_recursive(arr, ++iStart, --iLast);  
    }
}

void main()
{
    char cArray[] = {"A quick brown fox jumps over a lazy dog"};

    rev_str_recursive(cArray, 0, strlen(cArray)-1);
}

You need to modify the string, ie the input buffer to reverse() , instead of just printing it.

Doing this recursively seems a bit obnoxious, but should of course be possible.

Basically, I guess the printing becomes an assignment, something like this:

  1. Base: The reversal of an empty string is the empty string.
  2. Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.

Here is another way to reverse a string using recursion:

void reverseString(char* dest, char *src, int len) {
    if (src == NULL || len == 0)
        return;

    reverseString(dest, src + 1, len - 1);
    strncat_s(dest, len + 1, src, 1);
}

You can call like that:

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

#define STRING "Let's try this one."
#define SIZE 20

void main() {

    char* src = (char*)malloc(SIZE);
    char* dest = (char*)malloc(SIZE);

    strcpy_s(dest, SIZE, "");
    strcpy_s(src, SIZE, STRING);

    reverseString(dest, src, strlen(src));
    /* Do anything with dest. */
    // printf("%s\n", dest);

    free(src);
    free(dest);
}

This code is not executable :( You define int reverse but reverse function doesnt return any value

instead use this (using void):

#include<stdio.h>

main()
{
  char a[17]="abcdefg";
  reverse(a);
  printf("\n");
  system("PAUSE");
}
void reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
   }
   printf("%c",*a);
}        
#include <iostream>
using namespace std;

reverse( char *str)
{
    if (*str!='\0')
    {
       reverse(str+1);
       cout<<*str;
    }
//cout<<*str   when i am just printing here then why this is printing after one space ??
}

int main()
{   
    string a ;  
    cin>>a;   
    reverse(&a[0]); 
    return 0;
}

a little change in Emre Can Kucukoglu's answer . . . we can eliminate strncat_s

void revstr_rec(char *sstr, char *dstr, int len)
{
    int i = 0;
    if((! *sstr) || (! len) )
        return;

    revstr_rec(sstr + 1, dstr, len - 1);
    dstr[len - 1] = *sstr;

    return;
}

int main()
{
    char *sstr = NULL;
    char *dstr = NULL;

    sstr = malloc(16);
    if(! sstr)  {
        printf("no memory . . .\n");
        return 0;
    }
    strcpy(sstr, "hello world !");
    printf("sstr: %s\n", sstr);

    dstr = malloc(16);
    if(! dstr)  {
        printf("no memory . . .\n");
        return 0;
    }

    revstr_rec(sstr, dstr, strlen(sstr));
    printf("dstr(recursive): %s\n", dstr);

    free(sstr);
    free(dstr);

    return 0;
}
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX], *rev;
scanf("%s", str);
rev = reverse(str); 
printf("The reversed string is : %s\n", rev);
return 0;
}
char *reverse(char ch[])
   {
    static char r[MAX];
    static int i=0;
    if(*ch == '\0') return "";
    else 
   {
    reverse(ch+1);
    r[i++]=*ch;
   }
    return r;
   }
// Reverse string
char* reverse(char* str)
{
    if (*str == '\0')
        return str;

    char tmp = *str;
    strcpy(str, reverse(str + 1));
    str[strlen(str)] = tmp;
    return str;
}

use sprintf it will print your reversed string into buffer.

#include<stdio.h>

char *b;

main()
{
  char a[17]="abcdefg";
  char buffer[17];
  buffer[0]= '\0';
  b = buffer;
  reverse(a);
  printf("%s\n",buffer);
}
int reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
     sprintf(b,"%c",*a);
     b++;
   }

}
void palindromo(char *s)
{
    if(s[0] != '\0'){
        palindromo(s+1);
        printf("%c", s[0]);
    }
}

This is a small recursive function who print the string inverted.

#include<stdio.h>
#include<string.h>
void rev(char *);

int main()
{
    char s[]="Hello";
    printf("\n%s",s);
    rev(s);
    printf("\n%s",s);
    return 0;
}

void rev(char *s)
{
    static int i=0;
    static int j=0;
    if(j==0)                   //since static variable can be intitialized 
    {                          //only with a constant literal,to store 
        j=strlen(s)-1;         //length-1 in 1st function call, we can use 
    }                          //this trick.(condition satisfied only in 1st 
                               //function call)
    if(i<j)
    {
        char temp;
        temp=s[i];
        s[i]=s[j];             //Analogous to for(i=0,j=l-1;i<j;i++,j--)
        s[j]=temp;             //                { //swap code }
        i++;
        j--;
        rev(s);           
    }
}
#include<stdio.h>
void reverse(char *a);
main()
{
  char a[17]="abcdefg";
  reverse(a);
  printf("\n");
  system("PAUSE");
}
void reverse(char *a)
{
   if(*a!='\0')
   {   
     reverse(a+1);
   }
   printf("%c",*a);
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM