[英]Macro for concatenating two strings in C
我正在尝试定义一个宏,假设它采用2个字符串值并返回它们之间的一个空格连接。 似乎我可以使用除空间之外我想要的任何角色,例如:
#define conc(str1,str2) #str1 ## #str2
#define space_conc(str1,str2) conc(str1,-) ## #str2
space_conc(idan,oop);
space_conc
将返回“idan-oop”
我想要一些东西回归“idan oop”,建议?
尝试这个
#define space_conc(str1,str2) #str1 " " #str2
'##'用于连接符号,而不是字符串。 字符串可以简单地并置在C中,编译器将连接它们,这就是这个宏的作用。 首先将str1和str2转换为字符串(如果你像这个space_conc(hello, world)
一样使用它,请说“你好”和“世界”)并将它们放在彼此旁边,中间是简单的单空格字符串。 也就是说,由此产生的扩展将由编译器解释
"hello" " " "world"
它将连接到哪个
"hello world"
HTH
编辑
为了完整性,宏扩展中的'##'运算符就像这样使用,假设你有
#define dumb_macro(a,b) a ## b
如果被称为dumb_macro(hello, world)
将导致以下结果
helloworld
这不是一个字符串,而是一个符号,你可能会得到一个未定义的符号错误,说'helloworld'不存在,除非你先定义它。 这是合法的:
int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'
#define space_conc(str1, str2) #str1 " " #str2
printf("%s", space_conc(hello, you)); // Will print "hello you"
正确的做法是将2个字符串放在另一个旁边。 '##'不起作用。 只是:
#define concatenatedstring string1 string2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.