可能重复:
C 字符串连接
如何在 C 中连接多个 char 字符串?
例子:
const char *bytes = "tablr=Hello%20World";
const char *bytes2 = "tablr=Hello%20World";
const char *bytes3 = "tablr=Hello%20World";
谢谢
这是一个避免画家问题的建议:
char const *bytes = "tablr=Hello%20World";
char const *bytes2 = "tablr=Hello%20World";
char const *bytes3 = "tablr=Hello%20World";
unsigned int const sz1 = strlen(bytes );
unsigned int const sz2 = strlen(bytes2);
unsigned int const sz3 = strlen(bytes3);
char *concat = (char*)malloc(sz1+sz2+sz3+1);
memcpy( concat , bytes , sz1 );
memcpy( concat+sz1 , bytes2 , sz2 );
memcpy( concat+sz1+sz2 , bytes3 , sz3 );
concat[sz1+sz2+sz3] = '\0';
/* don't forget to free(concat) when it's not needed anymore */
这避免了画家的问题,并且应该更有效(尽管有时不是),因为 memcpy 可能会逐字节或逐字复制,具体取决于实现,这样更快。
如果你可以在这里看到一个模式,这可以很容易地转换成一个连接任意数量字符串的函数,如果它们是在 char const*[] 中提供的
通常,您strcat
使用<string.h>
.
但是您可以仅通过一个接一个地编写字符串文字来连接它们。例子:
const char *p = "Hello, " "World"
"!";
p 指向“你好,世界!”。
在你的情况下,它会是这样的:
const char* p =
"tablr=Hello%20World"
"tablr=Hello%20World"
"tablr=Hello%20World";
字符串文字可以简单地通过相邻来连接:
const char *whole_string = "tablr=Hello%20World" "tablr=Hello%20World" "tablr=Hello%20World";
上述连接由编译器完成,不会产生运行时开销。
包含(string.h
简单但“慢”(不是很慢;P)方式):
char * result = calloc(strlen(bytes)+strlen(bytes2)+strlen(bytes3)+1,sizeof(char));
strcat(result, bytes);
strcat(result, bytes2);
strcat(result, bytes3);
使用有效的循环:
int i, j, len = strlen(bytes)+strlen(bytes2)+strlen(bytes3)+1;
char * result = malloc(sizeof(char)*len);
for(i = 0; i < len && bytes[i] != '\0'; i++)
result[i] = bytes[i];
for(j = 0; i < len && bytes2[j] != '\0'; i++, j++)
result[i] = bytes2[j];
for(j = 0; i < len && bytes3[j] != '\0'; i++, j++)
result[i] = bytes3[j];
result[i] = '\0';
使用strcat
或strncat
功能。不过要小心周围的内存分配。
我建议使用 memcpy 功能。它非常有效:
int l1 = strlen(bytes), l2 = strlen(bytes2), l3 = strlen(bytes3);
int length = l1+l2+l3;
char *concatenatedBytes = (char *)malloc((length+1)*sizeof(char));
memcpy(concatenatedBytes, bytes, l1);
memcpy(concatenatedBytes + l1, bytes2, l2);
memcpy(concatenatedBytes + l1 + l2, bytes3, l3);
concatenatedBytes[length] = 0;
如果您的编译器支持它,请使用 strcat_s 或 _tcscat_s。他们将检查您正在写入的缓冲区长度。