[英]Concatenate strings recursively in C
我需要幫助在 C 中使用遞歸連接字符串。
我在輸入中有 2 個字符串, src和dest ,我需要遞歸地將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.