在C

时间:2018-05-17 23:40:25

标签: c string character concatenation

我正在学习C并尝试实现一项功能

char *es_cat(char *dst, char *src)

将字符串src添加到dst的末尾,但稍微扭曲:字符串被认为以'?'字符而不是通常'\0'结尾。创建的字符串必须以'?'结尾,但第一个字符串' s '?'将被忽略。这是我的尝试:

/* 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,即不创建缓冲区?

提前谢谢!

1 个答案:

答案 0 :(得分:1)

也许你的函数使用不同的字符串终止符,但你使用的仍然是标准的C函数来打印出字符串,并且它们需要一个空终止符char,所以最后你必须在字符串中写一个空终止符

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