[英]Create string from array of strings in C
我的任务是编写一个将char**
作为参数并返回char*
的函数。 char *必须指向以null结尾的字符串,该字符串是char **中每个字符串的串联。
我应该如何处理?
一些地方建议循环遍历char**
并使用strcat()
构建字符串,但是strcat(
)要求我有一个足够大的目的地来容纳最终的字符串; 而且我不知道该字符串将有多大。 我是否应该通过请求char**
的每个元素的strlen()
来找出它的大小?
用C做到这一点的最佳方法是什么?
可能的方法:
char**
,为每个条目累积strlen(char*)
的结果。 malloc()
为字符串分配内存,并将第一个字符设置为null终止符(以确保strcat()
首次正确运行)。 strcat()
再次进行迭代。 记录调用者负责free()
返回的字符串。
您可以通过两种主要方式执行此操作:
strlen
求和 NULL
字符串开始,然后遍历字符串。 当你重复你realloc
目标,以适应规模的增加 是的,您最好计算出所需的所有空间,以便为新字符串分配足够的空间。
在为所有字符串创建空格之后,只需在它们之间复制一个空格字符即可(但如果添加空格,请不要忘记为分配分配它们...)
您可能需要考虑以下注释的代码( 位于Ideone.com上的此处 )。
综上所述:
strlen()
求和输入字符串的长度。 malloc()
为结果字符串分配内存。 strcat()
再次遍历输入数组,并连接输入字符串。 #include <stdio.h> /* For printf() */
#include <stdlib.h> /* For malloc(), free() */
#include <string.h> /* For strcat(), strlen() */
/*
* Concatenates input strings into a single string.
* Returns the pointer to the resulting string.
* The string memory is allocated with malloc(),
* so the caller must release it using free().
* The input string array must have NULL as last element.
* If the input string array pointer is NULL,
* NULL is returned.
* On memory allocation error, NULL is returned.
*/
char * ConcatenateStrings(const char** strings)
{
int i = 0; /* Loop index */
int count = 0; /* Count of input strings */
char * result = NULL; /* Result string */
int totalLength = 0; /* Length of result string */
/* Check special case of NULL input pointer. */
if (strings == NULL)
{
return NULL;
}
/*
* Iterate through the input string array,
* calculating total required length for destination string.
* Get the total string count, too.
*/
while (strings[i] != NULL)
{
totalLength += strlen(strings[i]);
i++;
}
count = i;
totalLength++; /* Consider NUL terminator. */
/*
* Allocate memory for the destination string.
*/
result = malloc(sizeof(char) * totalLength);
if (result == NULL)
{
/* Memory allocation failed. */
return NULL;
}
/*
* Concatenate the input strings.
*/
for (i = 0; i < count; i++)
{
strcat(result, strings[i]);
}
return result;
}
/*
* Tests the string concatenation function.
*/
int main(void)
{
/* Result of string concatenation */
char * result = NULL;
/* Some test string array */
const char * test[] =
{
"Hello ",
"world",
"!",
" ",
"Ciao ",
"mondo!",
NULL /* String array terminator */
};
/* Try string concatenation code. */
result = ConcatenateStrings(test);
/* Print result. */
printf("%s\n", result);
/* Release memory allocated by the concatenate function. */
free(result);
/* All right */
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.