#include<stdio.h>
/* a function to merge two strings */
void stringMerge(char* f, char* s){
while(*f++);
while((*f++ = *s++));
}
int main(){
char s1[] = "Hello ";
char s2[] = "World";
stringMerge(s1,s2);
printf("%s",s1);
return 0;
}
-5
A
回答
-2
我建議你使用string.h
的strncat()
。這裏是你的代碼:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *s1 = "Hello ";
char *s2 = "World\n";
size_t s1_size = strlen(s1);
size_t s2_size = strlen(s2);
char *concat = calloc((s1_size + 1 + s2_size + 1), sizeof(char));
if (concat == NULL) {
perror("Calloc");
exit(EXIT_FAILURE);
}
strncat(concat, s1, s1_size);
strncat(concat, s2, s2_size);
printf("%s", concat);
free(concat);
return 0;
}
+0
'strncat(concat,s1,s1_size);'? 'concat'被*初始化*。 –
+0
什麼?我已經安裝了concat,然後是strncat。 –
+0
是的,但只是在我指出錯誤之後。你把'malloc'改成了'calloc'。 –
0
考慮到你要連接的字符串的聲明,那麼它似乎是你的意思是下面的函數實現。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * stringMerge(const char *s1, const char *s2)
{
size_t n = strlen(s1);
char *p = (char *)malloc(n + strlen(s2) + 1);
if (p)
{
strcpy(p, s1);
strcpy(p + n, s2);
}
return p;
}
int main(void)
{
char s1[] = "Hello ";
char s2[] = "World";
char *p = stringMerge(s1, s2);
puts(p);
free(p);
}
或下列
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char * stringMerge(const char *s1, const char *s2)
{
size_t n = strlen(s1);
char *p = (char *)malloc(n + strlen(s2) + 1);
if (p)
{
char *t = p;
while (*t = *s1++) ++t;
do { *t = *s2++; } while (*t++);
}
return p;
}
int main(void)
{
char s1[] = "Hello ";
char s2[] = "World";
char *p = stringMerge(s1, s2);
puts(p);
free(p);
}
在這兩個程序的輸出是
Hello World
相關問題
- 1. 如何合併兩個字符串爲一個字符串在Java中
- 2. 合併兩個JSON字符串
- 3. 合併兩個json字符串
- 4. 合併兩個字符串列表
- 5. 合併xslt中的兩個字符串
- 6. 如何使用逗號將字符串拆分爲兩個字符串並存儲字符串? (C++)
- 7. 組合兩個字符串
- 8. 組合兩個字符串
- 9. 在.NET/C#2.0中合併兩個字符串數組?
- 10. 將兩個不同大小的字符串合併爲C
- 11. 如何在Spark中合併兩個RDD [字符串]?
- 12. 如何在javascript中交替合併兩個字符串?
- 13. 如何合併兩個字符串列表中的重複項?
- 14. 如何在python中合併兩個字符串?
- 15. 如何在Java中合併兩個json字符串
- 16. 我如何將兩個字符組合成一個字符串c#
- 17. 基於字符索引合併兩個字符串
- 18. C:兩個字符串
- 19. 如何使用C中的宏連接兩個寬字符串?
- 20. 如何合併兩個字符串我Haskell並返回一個新的字符串
- 21. 混合C++字符串使用C
- 22. 如何將C中兩個字符串的字符隨機組合在一起?
- 23. 如何使用兩個分隔符的字符串獲得子串(和)在C++
- 24. Python如何掃描字符串並在兩個字符之間使用upper()?
- 25. 如何找到一個字符串模式,並使用C#
- 26. 在Python中合併兩個JSON字符串,並使用值列表
- 27. 合併兩個字符串並按日期/時間排序
- 28. 如何合併使用Python的CSV字符串中的字段?
- 29. 如何將binarySearch集合應用於兩個字符串ararylist
- 30. 字符串不會合並 - 目標C
's1'具有6個字符的空間(7個字節與''\ 0'') ; 's2'有5個字符的空間(6個字節)。你沒有一個能夠保存11個字符的對象(12個字節用於「'\ 0'')。 – pmg
@roch標準C函數strcat還是你自己寫的函數? –
'while(* f ++);'==>'while(* f)f ++;'否則你會跳過字符串終止符而不是覆蓋它。 –