2012-04-24 59 views
16

One of the answersWhy do you not use C for your web apps?包含以下內容:C字符串拼接

For the C crap example below:

const char* foo = "foo"; 
const char* bar = "bar"; 
char* foobar = (char*)malloc(strlen(foo)+strlen(bar)+1); 
strcpy(foobar, foo); 
strcat(foobar, foo); 

Actually, constants CAN AND SHOULD be concatenated naturally in C:

const char foo[] = "foo"; 
const char bar[] = "bar"; 
char foobar[] = foo bar; // look Ma, I did it without any operator! 

And using [] instead of * will even let you modify the string, or find their length:

int foo_str_len = sizeof(foobar)-1; 

So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.


我已經嘗試過自己,但得到一個錯誤:

expected ‘,’ or ‘;’ before string constant

所以我的問題是:做我需要告訴編譯器,爲了使這個工作或上述帖子簡直是錯誤的?請注意,我知道用C連接字符數組的其他方法。

+15

這個答案是無稽之談。 – 2012-04-24 09:59:51

回答

33

(char*)malloc

決不強制轉換的C.閱讀thisthis的malloc的結果。

Actually, constants CAN AND SHOULD be concatenated naturally in C

否,字符串文字可以和應該C. "foo"級聯是一個字符串文字和const char foo[]是一個常數字符串(字符數組)。代碼"foo" "bar"將自動連接,代碼foo bar不會。

如果你願意,你可以隱藏的字符串常量宏背後:

#define foo "foo" 
#define bar "bar" 
char foobar[] = foo bar; // actually works 

So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.

Ç相當困難與串用,因爲我們可以從這個例子很看。儘管他們的傲慢自信,誰寫的人混在一起的各種概念,仍然必須學習如何使用C.

+0

+1感謝您的詳細解答。 – 2012-04-24 13:02:28

+0

@Lundin用''foo「bar()'做這個工作,其中'bar()'返回一個'char *'? – 2015-01-15 23:52:51

+1

@AlexejMagura char *不是一個字符串,所以沒有。 – Lundin 2015-01-16 07:20:18

7

答案看起來像某人設法將字符串文字(可以用這種方式連接)與const字符串變量進行混合。我的猜測是原來有預處理宏而不是變量。

-1
#include <stdio.h> 
#include <string.h> 

int 
main(int argc, char *argv[]) 
{ 
    char *str1 = "foo"; 
    char *str2 = "bar"; 
    char ccat[strlen(str1)+strlen(str2)+1]; 

    strncpy(&ccat[0], str1, strlen(str1)); 
    strncpy(&ccat[strlen(str1)], str2, strlen(str2)); 
    ccat[strlen(str1)+strlen(str2)+1] = '\0'; 

    puts(str1); 
    puts(str2); 
    puts(ccat); 
} 

此代碼連接str1str2無需malloc,輸出應該是:

foo 
bar 
foobar 
+0

是的,我知道,我忘了退出退出狀態 – Raiz 2016-07-27 09:56:47

+0

請不要再次。 SO不是教程網站。 – Michi 2016-07-27 10:15:16