1

我正在尝试使用递归将文本文件中的字符串反转到另一个文本文件中。反转的字符串将存储在 char 数组中,缓冲区将成为该数组。然后缓冲区将被 fprintf 编辑到新文件中。这就是我到目前为止所拥有的。

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

        int
        reverse(char *ch, char *str)    //receives "buffer" as argument. str traverses ch
        {
            char array[20]; //will store the reversed string

            if(*str == '\0')
                return 0;   //arrived at end of string
            return(reverse(ch, str+1) + 1);      //don't know if this is correct
        }

//I want to use the returned number as the index number. For example, if I have
//string "abcd", string[0]='d', string[1]='c', string[2]='b', string[3]='a'. Problem is,
//how do I do it?


        int main(int argc, char *argv[])    //argv[1] is input file. argv[2] is output file printed backwards
        {   
            FILE *fp1, *fp2;
            char *p, buffer[20];    //p points to buffer

            fp1 = fopen("a.txt", "r");
            if(fp1 == NULL)
            {
                printf("The file does not exist.\n");
                return 0;
            }

            p = buffer;
            while(fgets(buffer, 20, fp1) != NULL)   //reads the first 20 characters of file.txt into buffer
            {
                reverse(buffer, p); //passes "buffer" as argument
                fprintf(fp2, "%s\n", buffer);
            }

            printf("File %s has been successfully reversed into file %s!\n", argv[1], argv[2]);
            fclose(fp1);
            fclose(fp2);
            return 0;
        }

由于我是递归新手,所以我对如何实现我的反向函数只有最微弱的想法。

4

1 回答 1

1

通过迭代循环反转字符串更容易和更快,但是要创建递归函数,您可以让函数反转开始和结束字符,然后用较小的字符串重复该过程

abcde 
^   ^  first call
 ^ ^   next call
  ^    end

---

void reverse(char *s, char *e) {
  char tmp = *s;
  *s++ = *e;
  *e-- = tmp;
  if (e > s) reverse (s, e);
}

其中s指向第一个字符,e指向最后一个字符。请注意,初始字符串的长度必须 > 0(或者可以将测试添加到函数中)。

示例

int main () {
    char x[] = "abcde";  
    reverse(x, x+strlen(x)-1);  
    printf("%s\n", x);  
    return 0;  
}  

输出edcba

于 2013-02-27T06:01:54.397 回答