繁体   English   中英

在 C 中递归连接字符串

[英]Concatenate strings recursively in C

我需要帮助在 C 中使用递归连接字符串。

我在输入中有 2 个字符串, srcdest ,我需要递归地将src连接到dest ,并将连接后的字符串存储在dest 中

例如,如果src="house"dest="clock" ,输出应该是"chlooucske"

编辑:这是我的代码:

char* str_concatenate(char dest[], char src[], int index){
    char temp[256]; // temporaty variable
    temp[index]=src[index]; //should copy each letter from src to temp
    temp[index+1]=dest[index]; //should copy each letter from dest to temp
    dest[index]=temp[index]; //should store the concatenated string into dest
    if (src[index]=='\0'){ //base case
        return dest;
    }
    else
        return str_concatenate(dest,src,index+1);
}

int main(){ //test
        char dest[]="house";
        char src[]="clock";

        char* ris=str_concatenate(dest,src,0);

        printf("dest= %s\n", ris); //should print "chlooucske" 
    return 0;
    }

但是它将整个单词从src复制到dest并打印出来,它不会连接字母。

目标指针指向一个字符串常量。 您正在尝试修改它,它会导致您的程序崩溃。 您可以使用数组并将其初始化为目标字符串。

你可能想看看这个。 这解释了你的问题。 char s[] 和 char *s 有什么区别?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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