开发者

Group multiple strings into one in C

I want to create a "fullname" variable from multiple strings. Something like this:

strcpy (开发者_开发知识库fullname, firstname);
strcat (fullname, separator); // separator is initialized at " "
strcat (fullname, middlename);
strcat (fullname, separator);
strcat (fullname, lastname);

This code is repeated at multiple places in my project. I was gonna do a function that does exactly that, but now I wonder if there isn't a better way to do it.

Any ideas?


You can do also:

sprintf (fullname, "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

But always make sure that the fullname points to a buffer which can accommodate the total length of all the things you are concatenating.

int size;
int *fullname;
size = strlen (firstname) + strlen (separator) + strlen (middlename) + strlen (separator) + strlen (lastname) + 1;

fullname = malloc (sizeof (char) * size);

sprintf (fullname, "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

/* Work */

free (fullname);


sprintf(fullname, "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);

If separator is always " " then you can do

sprintf(fullname, "%s %s %s", firstname, middlename, lastname);

Though you need to ensure that fullname has sufficient space.


There's stpcpy (became standard in posix 2008). It'd look like this:

char *ptr = fullname:
ptr = stpcpy (ptr, firstname);
ptr = stpcpy (ptr, separator);
ptr = stpcpy (ptr, middlename);
ptr = stpcpy (ptr, separator);
ptr = stpcpy (ptr, lastname);

If you also need to take care not to overflow fullname, use stpncpy instead:

char *ptr = fullname;
char *end = fullname + sizeof(fullname) - 1;
ptr = stpncpy (ptr, firstname, end - ptr);
ptr = stpncpy (ptr, separator, end - ptr);
ptr = stpncpy (ptr, middlename, end - ptr);
ptr = stpncpy (ptr, separator, end - ptr);
ptr = stpncpy (ptr, lastname, end - ptr);
*ptr = '\0'; // Or optionally error if ptr >= end

snprintf can also be a good choice:

snprintf(fullname, sizeof(fullname), "%s%s%s%s%s", firstname, separator, middlename, separator, lastname);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜