问题描述
我有什么:
char * a = "world";
char * b = "Hello";
我需要的是:
char * a = "Hello World";
我需要前加湾
是否有这样做的任何功能?
I need to add b before a.Is there any function that doing it?
推荐答案
您可以使用的,或
使用 strcat的
你需要核对(使用 ... )
随着 strcat的
&安培; 的snprintf
,你需要pre-分配数组。
随着 asprintf
您将得到一个堆分配的缓冲区作为一个结果,你会适当地需要免费
它。
With strcat
you need to check against buffer overflow (using strlen(3)...)With strcat
& snprintf
, you need to pre-allocate the array.With asprintf
you are given a heap-allocated buffer as a result, and you'll need to free
it appropriately.
因此,使用 strcat的
和一个固定大小的缓冲区 BUF
:
So, using strcat
and a fixed-size buffer 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
失败:如果(!BUF){PERROR(BUF的malloc);出口(EXIT_FAILURE); };
然后执行的strcpy
&安培; strcat的
如前。当然,你需要免费(BUF)
以后在适当的时候。请注意,您可以保留 INT莉娜= strlen的(A);
然后的strcpy(BUF +莉娜,B)
而不是调用 strcat的
。
Alternatively you might use a heap-allocated buffer:
char*buf = malloc(strlen(a)+strlen(b)+1);
but don't forget to check against malloc
failure: if (!buf) { perror("malloc buf"); exit(EXIT_FAILURE); };
and then do the strcpy
& strcat
as before. Of course you'll need to free(buf)
later at the appropriate time. Notice that you could keep int lena=strlen(a);
then strcpy(buf+lena,b)
instead of calling strcat
.
使用的snprintf
和一个固定大小的缓冲区 BUF
(无需检查抗缓冲区溢出,因为的snprintf
给定缓冲区大小):
Using snprintf
and a fixed-size buffer buf
(no need to check against buffer overflow since snprintf
is given the buffer size):
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
浮点科学计数法,等...)
The nice thing about snprintf
is that is understands printf
format control strings (e.g. %d
for integer in decimal, %g
for floating point in scientific notation, etc...)
使用 asprintf
(像Linux系统上提供了哪些吧)
Using asprintf
(on systems like Linux which provide it)
char* buf = asprintf("%s%s", a, b);
但你需要调用免费(BUF)
在适当的时候,以避免的。
But you need to call free(buf)
at the appropriate moment to avoid a memory leak.
又见,的和 open_memstream
这篇关于为char * preFIX添加在C现有的char *最好的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!