[英]Concatenating strings while passing as argument to function
There is a function that takes string as a parameter/argument. 有一个函数将字符串作为参数/参数。
Func(char* strA)
{
...
}
I have two strings; 我有两个琴弦;
#define FIRST "first"
char efg[] = " second";
I want to basically send "first second"
as argument to Func(strA)
, but I do not want to use strcat(FIRST, efg);
我基本上想将
"first second"
作为参数发送给Func(strA)
,但是我不想使用strcat(FIRST, efg);
as it would permanently change my macro FIRST
. 因为它将永久更改我的宏
FIRST
。
Is there a way to send "first second"
as argument without upsetting the macro above? 有没有一种方法可以发送
"first second"
作为参数而不破坏上面的宏?
You can use of sprintf function to write first in a temp buffer: 您可以使用sprintf函数先在临时缓冲区中写入:
#define FIRST "first"
char efg[] = " second";
char* space = " ";
char* strA = calloc(strlen(FIRST) + strlen(space) + strlen(efg) + 1, sizeof(char));
sprintf(strA,"%s%s%s",FIRST, space, efg);
Func(strA);
free(strA);
Give it a Try!! 试试看!!
Note: don't forget free() dynamic allocated memory. 注意:不要忘记free()动态分配的内存。
Description: 描述:
The sprintf()
function is just like printf()
, except that the output is sent to buffer. sprintf()
函数类似于printf()
,只是输出被发送到缓冲区。 The return value is the number of characters written. 返回值是写入的字符数。
If it's permissable to you not to have efg
as a variable but as a string literal, then because adjacent string literals are implicitly concatenated (spec C99: 5.1.1.2.6) you could simply have the following: 如果允许您不要让
efg
作为变量而是作为字符串文字,那么由于隐式级联了相邻的字符串文字(规范C99:5.1.1.2.6),您可以简单地拥有以下内容:
Func(FIRST " second");
And for the same reason you could alternatively declare efg
as 出于同样的原因,您也可以将
efg
声明为
char efg[] = FIRST " second";
Either way, much easier than strcat or sprintf. 无论哪种方式,都比strcat或sprintf容易得多。
也许您可以先使用strcpy()
将宏复制到新的char数组,然后使用strcat( new_var, efg )
-将其作为参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.