2015-04-05 35 views
1

我知道我可以有一個語句,這樣的strcat來連接A和B,而無需實際改變a或b

strcat(a, b); 
    int alen = strlen(a); 
    printf("a and b concatenated = %s and its length is %d\n", a, alen); 

不過,我想保留一個,所以我想用更多的東西是這樣的:

strcat(a, b); 
    int xlen = strlen(x); 
    printf("a and b concatenated = %s and its length is %d\n", x, xlen); 

如何用strcat修復第一行,以便將a和b連接成x?

回答

4

你應該使用下列內容: -

strcpy(x,a); 
strcat(x,b); 
int xlen = strlen(x); 
printf("a and b concatenated = %s and its length is %d\n", x, xlen); 

瞧,這就是它。

+1

謝謝你,這是很簡單的。 – tinkerton101 2015-04-05 19:56:26

+1

有一個重要的細節總是要檢查。具體而言,如果SIZE1和SIZE2與strlen(a)和strlen(b)相關,那麼x的長度足以保存strlen(a)+ strlen(b)+1 – user3629249 2015-04-06 22:10:35

0

我發現下面的作品,以及:

/* Concatenate a and b */ 
    char x[SIZE1+SIZE2] = 「」; 
    strcat(x , a); 
    strcat(x , b); 

    printf("a and b concatenated = %s and its length is %d\n", x, (int)strlen(x)); 
+1

,那麼結果不夠大,因爲strlen()是尾隨NUL字節的偏移量,因此需要添加+1以獲得適當的長度。另外,第一行導致x [0]包含'\ 0'。它並沒有清除所有的x []。建議使用:; char x [SIZE1 + SIXE2 + 1] = {'\ 0'};清除整個數組,並且不會在只讀內存中生成文字(僅包含'\ 0'字符) – user3629249 2015-04-06 22:15:48

相關問題