【发布时间】:2015-01-08 06:59:38
【问题描述】:
我有什么:
char * a = "world";
char * b = "Hello";
我需要的是:
char * a = "Hello World";
我需要在 a 之前添加 b。 有什么功能可以做到吗?
【问题讨论】:
-
最简单的方法是使用新字符串。
我有什么:
char * a = "world";
char * b = "Hello";
我需要的是:
char * a = "Hello World";
我需要在 a 之前添加 b。 有什么功能可以做到吗?
【问题讨论】:
如下图即可轻松完成:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char * a = "world";
char * b = "Hello";
char *c = malloc(strlen(a)+strlen(b)+1);
strcpy(c,b);
strcat(c,a);
printf("%s\n",c);
free(c);
}
【讨论】:
您可以使用strcat(3)、snprintf(3) 或asprintf(3)
使用strcat,您需要检查buffer overflow(使用strlen(3)...)
使用strcat & snprintf,您需要预先分配数组。
使用asprintf,您将获得一个堆分配的缓冲区,您需要适当地free。
所以,使用strcat 和一个固定大小的缓冲区buf:
char buf[64];
if (strlen(a)+strlen(b)<sizeof(buf)) {
strcpy(buf, a);
strcat(buf, b);
}
// now buf contains "worldhello"
或者,您可以使用堆分配的缓冲区:char*buf = malloc(strlen(a)+strlen(b)+1);,但不要忘记检查 malloc 失败:if (!buf) { perror("malloc buf"); exit(EXIT_FAILURE); };,然后像以前一样执行 strcpy 和 strcat。当然,您需要稍后在适当的时候free(buf)。请注意,您可以先保留int lena=strlen(a);,然后再保留strcpy(buf+lena,b),而不是调用strcat。
使用snprintf 和固定大小的缓冲区buf(无需检查缓冲区溢出,因为snprintf 已指定缓冲区大小):
char buf[54];
int len= snprintf(buf, sizeof(buf), "%s%s", a, b);
// now buf contains "worldhello" and len contains the required length
snprintf 的好处在于它可以理解 printf 格式控制字符串(例如,%d 用于十进制整数,%g 用于科学记数法中的浮点等...)
使用asprintf(在提供它的 Linux 等系统上)
char* buf = asprintf("%s%s", a, b);
但您需要在适当的时候致电free(buf) 以避免memory leak。
另请参阅strdup(3)、fmemopen(3) 和 open_memstream
在您的问题中,您应该交换 a 和 b
【讨论】: