如何连接 C
中的多个字符串?
我有一个用于连接两个字符串的函数(没有 strcat()
):
char* concat(char *s1, char *s2)
{
char *r, *t;
int d1 = -1, d2 = -1;
while (s1[++d1]);
while (s2[++d2]);
t = r = (char *)calloc(d1 + d2 + 1, sizeof(char));
while (*t++ = *s1++);
t--;
while (*t++ = *s2++);
return r;
}
有没有办法使用此函数(或 strcat()
)来连接多个字符串?
另外,这种动态分配是否正确:
char* concat(char** array, int n)
{
char *r; int i;
r=(char *)calloc(n*MAX+1, sizeof(char));
array=(char **)malloc(n * sizeof(char *));
for(i=0;i<n;i++)
{
array[i]=(char *)malloc(MAX+1);
}
... //concatenation//...
free(r);
free(array[i]);
free(array);
return r;
}
最佳答案
是的,您可以扩展第一个函数的代码来处理整个数组:
char* concat(char** array, size_t n) {
size_t total = 1; // One for null terminator
for (int i = 0 ; i != n ; i++) {
total += strlen(array[i]);
}
char *res = malloc(total);
char *wr = res;
for (int i = 0 ; i != n ; i++) {
char *rd = array[i];
while ((*wr++ = *rd++))
;
wr--;
}
*wr = '\0';
return res;
}
您不需要分配临时 2D 结构。由于您可以预先计算结果的长度,因此一次分配就足够了。
关于C: 'n'字符串的串联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29302178/