简体   繁体   English

在 C 中递归连接字符串

[英]Concatenate strings recursively in C

I need help to concatenate strings using recursion in C.我需要帮助在 C 中使用递归连接字符串。

I have 2 strings in input, src and dest , and I need to concatenate recursively src to dest , and store the concatenated string in dest .我在输入中有 2 个字符串, srcdest ,我需要递归地将src连接到dest ,并将连接后的字符串存储在dest 中

eg if src="house" and dest="clock" , the output should be "chlooucske" .例如,如果src="house"dest="clock" ,输出应该是"chlooucske"

EDIT: This is my code:编辑:这是我的代码:

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

However it copies the entire word from src to dest and prints it, it does not concatenate letters.但是它将整个单词从src复制到dest并打印出来,它不会连接字母。

The destination pointer is pointing to a string constant.目标指针指向一个字符串常量。 You are trying to modify it and it causes your program to crash.您正在尝试修改它,它会导致您的程序崩溃。 You can use an array and initialize it as the destination string.您可以使用数组并将其初始化为目标字符串。

You may want to take a look at this.你可能想看看这个。 This explains your problem.这解释了你的问题。 What is the difference between char s[] and char *s? char s[] 和 char *s 有什么区别?

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

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