我正在学习C并试图实现一个函数char *es_cat(char *dst, char *src)
这会将字符串src
添加到dst
的结尾,但有一点扭曲:字符串被视为以'?'
字符结尾,而不是通常的'\0'
字符。创建的字符串必须以'?'
结尾,但第一个字符串的'?'
将被忽略。我的尝试是:
/* A simple function to determine the length of a string according to the
* previously stated '?' constraint.
*/
unsigned int es_length(const char *s)
{
const char *c = s;
int amount = 0;
while (*c != '?')
{
amount++;
c++;
}
return amount;
}
char *es_cat(char *dst, char *src)
{
int total = es_length(dst) + es_length(src) + 1; // + 1 for the last '?'
char buffer[total];
char *b = buffer;
/* Copy the dst string. */
while (*dst != '?')
{
*b = *dst;
dst++;
b++;
}
/* Concatenate the src string to dst. */
while (*(src-1) != '?')
{
*b = *src;
src++;
b++;
}
printf("\n%s", buffer);
return buffer;
}
int main(void)
{
char cat_dst[] = "Hello ?"; // length according to es_length = 6
char cat_src[] = "there! - Well hel?"; // length according to es_length = 17
es_cat(cat_dst, cat_src);
return 0;
}
现在,当我运行时,我期望输出:
Hello there! - Well hel?
。字符串基本上是相同的,但是后面跟着3个字符的垃圾(准确地说,输出现在是Hello there! - Well hel?■@
)。当我从cat src char数组中添加或删除3个字符时,垃圾桶字符将消失。我是在错误地初始化缓冲区,还是在用指针弄乱某些东西?另一方面,是否可以直接连接字符串
dst
即不创建缓冲区?提前谢谢你!
最佳答案
也许您的函数使用不同的字符串终止符,但是您仍然使用标准的C函数来打印字符串,并且它们需要一个空终止符字符,因此,在最后,您必须将一个空终止符写入字符串。
char *es_cat(char *dst, char *src)
{
int total = es_length(dst) + es_length(src) + 2; // + 1 for the last '?' and +1 for the '\0'
char *buffer = (char*)malloc(total);
char *b = buffer;
if (buffer == NULL)
return NULL;
/* Copy the dst string. */
while (*dst != '?')
{
*b = *dst;
dst++;
b++;
}
/* Concatenate the src string to dst. */
while (*src != '?')
{
*b = *src;
src++;
b++;
}
*b = '?';
b++;
*b = '\0';
printf("\n%s", buffer);
return buffer;
}
关于c - 用C中的特殊结束字符连接字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50401879/