C 不支持其他一些语言所具有的字符串。 C中的字符串只是一个指向数组的指针char
由第一个空字符终止。 C中没有字符串连接运算符。
Use strcat
连接两个字符串。您可以使用以下函数来完成此操作:
#include <stdlib.h>
#include <string.h>
char* concat(const char *s1, const char *s2)
{
char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
这不是最快的方法,但您现在不必担心。请注意,该函数将一块堆分配的内存返回给调用者,并传递该内存的所有权。调用者有责任free
当不再需要内存时。
像这样调用该函数:
char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string
如果您确实对性能感到困扰,那么您会希望避免重复扫描输入缓冲区以查找空终止符。
char* concat(const char *s1, const char *s2)
{
const size_t len1 = strlen(s1);
const size_t len2 = strlen(s2);
char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
// in real code you would check for errors in malloc here
memcpy(result, s1, len1);
memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
return result;
}
如果您计划使用字符串进行大量工作,那么您最好使用对字符串具有一流支持的不同语言。