简体   繁体   中英

Recursively reversing a string in C?

I have to reverse a string in a recursive function, but I cannot use loops or strlen to find where the end of the string is. Then I have to pass the reversed string back to main and copy it to a new file. Here's what I have so far:

int reverse(char *str, char *strnew, int p)
{
    char temp=str[p];
    if(temp=='\0' || temp=='\n')
    {
            strnew=str;
            return p;
    }
    else
    {
            reverse(str++, strnew, ++p);
            p--;
            strnew[p]=str[p];
            printf("strnew: %c\n",  strnew[p]);
            return 0;
    }
}



int main(int argc, char *argv[])
{
    FILE *fp;
    char buffer[100];
    char newstr[100];
    int pointer=0;
    fp=fopen("lab8.txt", "r");
    if(fp==NULL)
    {
            printf("Error opening file\n");
            return 0;
    }
    (fgets(buffer, 100, fp));
    reverse(buffer, newstr, pointer);
    printf("newstr: %s\n", newstr);
    FILE *fp2=fopen("lab8.2.txt", "w");
    fputs(newstr, fp2);
    fclose(fp);
    fclose(fp2);

    return 0;
}

I cannot wrap my head around how to reverse the string. I've found where the null character is using p, but how do I copy the string backwards onto a new string?

#include <stdio.h>

int reverse(char *str, int pos){
    char ch = str[pos];
    return (ch == '\0')? 0 : ((str[pos=reverse(str, ++pos)]=ch), ++pos);
}

int main(){
    char buffer[100];

    scanf("%99[^\n]", buffer);
    reverse(buffer, 0);
    fprintf(stdout, "%s\n", buffer);
    return 0;
}

Since this is obviously homework, no complete solution, only ideas.

First, you don't need to limit yourself to one recursive function. You can have several, and a resursive implementation of strlen is trivial enough. my_strlen(char *p) evaluates to 0 if *p = 0, and to 1 + my_strlen(p+1) otherwise.

You can probably do it in a single recursion loop, too, but you don't have to.

One more thing: as you recurse, you can run your code both on the front end of recursion and on the back end. A recursion is like a loop; but after the nested call to self returns, you have a chance to perform another loop, this one backwards. See if you can leverage that.

It is quite simple. When you enter the string, you save the character at the position you are are. Call the method recursively more character to the right. When you get to the end of the string, you will have N stack frames, each holding one character of an N character string. As you return, write the characters back out, but increment the pointer as you return, so that the characters are written in the opposite order.

I'll try to be nice and give you a little sample code. With some explanation.

The beauty of recursion is that you don't need to know the length of the string, however the string must be null terminated. Otherwise you can add a parameter for the string length.

What you need to think is that the last input character is your first output character, therefore you can recurse all the way to the end until you hit the end of the string. As soon as you hit the end of the string you start appending the current character to the output string (initially set to nulls) and returning control to the caller which will subsequently append the previous character to the output string.

void reverse(char *input, char *output) {
    int i;
    if(*input) /* Checks if end of string */
        reverse(input+1,output); /* keep recursing */
    for(i=0;output[i];i++); /* set i to point to the location of null terminator */
    output[i]=*input; /* Append the current character */
output[i+1]=0; /* Append null terminator */
} /* end of reverse function and return control to caller */

Finally, lets test the function.

int main(argc, argv) {
    char a[]="hello world";
    char b[12]="\0";
    reverse(a,b);
    printf("The string '%s' in reverse is '%s'\n", a, b);
}

Output

The string 'hello world' in reverse is 'dlrow olleh'

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