In C, "strings" are just plain char
arrays.
(在C语言中,“字符串”只是纯char
数组。)
Therefore, you can't directly concatenate them with other "strings". (因此,您不能将它们与其他“字符串”直接连接。)
You can use the strcat
function, which appends the string pointed to by src
to the end of the string pointed to by dest
:
(您可以使用strcat
函数,它将src
指向的字符串附加到dest
指向的字符串的末尾:)
char *strcat(char *dest, const char *src);
Here is an example from cplusplus.com :
(这是来自cplusplus.com的示例 :)
char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");
For the first parameter, you need to provide the destination buffer itself.
(对于第一个参数,您需要提供目标缓冲区本身。)
The destination buffer must be a char array buffer. (目标缓冲区必须是char数组缓冲区。)
Eg: char buffer[1024];
(例如: char buffer[1024];
)
Make sure that the first parameter has enough space to store what you're trying to copy into it.
(确保第一个参数有足够的空间来存储您要复制到其中的内容。)
If available to you, it is safer to use functions like: strcpy_s
and strcat_s
where you explicitly have to specify the size of the destination buffer. (如果可以使用,则使用诸如strcpy_s
和strcat_s
类的函数strcpy_s
安全,在这些函数中,您必须明确指定目标缓冲区的大小。)
Note : A string literal cannot be used as a buffer, since it is a constant.
(注意 :字符串文字不能用作缓冲区,因为它是一个常量。)
Thus, you always have to allocate a char array for the buffer. (因此,您始终必须为缓冲区分配一个char数组。)
The return value of strcat
can simply be ignored, it merely returns the same pointer as was passed in as the first argument.
(可以简单地忽略strcat
的返回值,它仅返回与作为第一个参数传入的指针相同的指针。)
It is there for convenience, and allows you to chain the calls into one line of code: (它在那里是为了方便起见,它允许您将调用链接到一行代码中:)
strcat(strcat(str, foo), bar);
So your problem could be solved as follows:
(因此,您的问题可以通过以下方式解决:)
char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);