gpt4 book ai didi

在 C 中递归连接字符串

转载 作者:行者123 更新时间:2023-11-30 20:54:51 26 4
gpt4 key购买 nike

我需要帮助在 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 并打印出来,它不会连接字母。

最佳答案

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

您可能想看看这个。这解释了你的问题。 What is the difference between char s[] and char *s?

关于在 C 中递归连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36954111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com