2012-04-24 52 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