递归扭转在C字符串? [英] Recursively reversing a string in C?

查看:104
本文介绍了递归扭转在C字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要扭转一个递归函数的字符串,但我不能使用循环或strlen的寻找到字符串的到底是什么。然后,我要反转字符串传递回主,并将其复制到一个新文件。这是我到目前为止有:

  INT扭转(的char * str中,字符* strnew,INT P)
{
    焦炭TEMP = str中[P]。
    如果(临时=='\\ 0'||气温=='\\ n')
    {
            strnew =海峡;
            回磷;
    }
    其他
    {
            反转(STR ++,strnew,++ P);
            P--;
            strnew [P] = STR [P];
            的printf(strnew:%C \\ N,strnew [P]);
            返回0;
    }
}INT主(INT ARGC,CHAR *的argv [])
{
    FILE * FP;
    炭缓冲器[100];
    焦炭中newstr [100];
    INT指针= 0;
    FP = FOPEN(lab8.txt,R);
    如果(FP == NULL)
    {
            的printf(打开文件时出错\\ n);
            返回0;
    }
    (与fgets(缓冲器,100,FP));
    反向(缓冲,中newstr,指针);
    的printf(中newstr:%S \\ n,中newstr);
    FILE * FP2 =的fopen(lab8.2.txt,W);
    的fputs(中newstr,FP2);
    FCLOSE(FP);
    FCLOSE(FP2);    返回0;
}

我不能换我围​​绕如何扭转线头。我发现那里的空字符是用P,但我怎么向后复制字符串到一个新的字符串?


解决方案

 的#include<&stdio.h中GT;INT反向(的char * str中,诠释POS){
    焦炭CH =海峡[POS]
    回报(CH =='\\ 0')? 0:((STR [POS =反转(STR,++ POS)] = CH),++ POS)
}诠释主(){
    炭缓冲器[100];    scanf函数(%99 [^ \\ n],缓冲区);
    扭转(缓冲液,0);
    fprintf中(标准输出,%S \\ n,缓冲区);
    返回0;
}

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;
}

这篇关于递归扭转在C字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆