【发布时间】:2020-02-29 09:05:54
【问题描述】:
我必须编写一个程序,它接受一个字符串参数,例如“abcd”,并返回一个新字符串,例如“a-bb-ccc-dddd”。所以对于字符串中的每个字符,在新字符串中增加它的重复。
在 C# 或 Java 中,我只会使用 StringBuilder,但在 C 中,我不确定如何检查字符串是否有足够的空间容纳新字符。如果没有,请重新分配。
char *str = malloc(strlen(source) * sizeof(char));
for (int i = 0; i <= strlen(source) - 1; i++)
(for int j = 0; j < i + 1; j++)
if (space_exists_in_string(source))
str[j] = source[i];
else {
str = realloc(str, strlen(str) * 2);
str[j] = source[i]
}
所以基本上我正在寻找一种方法来检查是否(space_exists_in_string)。
谢谢
【问题讨论】:
-
您必须使用变量来跟踪自己。例如:
size_t bytes = strlen(source); str = malloc (bytes);。后来:bytes *= 2; str = realloc(str, bytes); -
为什么不预先分配最终字符串的完整大小?从您的示例看来,您似乎可以计算出等于
n * (n + 1) / 2的第一个n数字(其中n是字符串的长度)的总和加上'-' 的数量,即@ 987654327@.
标签: c arrays string memory malloc