在C中将多个字符串分组为一个

时间:2011-08-21 12:40:01

标签: c string

我想从多个字符串创建一个“fullname”变量。像这样:

strcpy (fullname, firstname);
strcat (fullname, separator); // separator is initialized at " "
strcat (fullname, middlename);
strcat (fullname, separator);
strcat (fullname, lastname);

此代码在我的项目中的多个位置重复。我会做一个完全正确的功能,但现在我想知道是否有更好的方法来做到这一点。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

你也可以这样做:

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

但总是要确保fullname指向缓冲区,该缓冲区可以容纳所有连接事物的总长度。

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);

答案 1 :(得分:1)

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

如果分隔符始终为" ",则可以执行

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

虽然您需要确保fullname有足够的空间。

答案 2 :(得分:1)

stpcpy(在posix 2008中成为标准)。它看起来像这样:

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

如果您还需要注意不要溢出fullname,请改用stpncpy:

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也是一个不错的选择:

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