C - 在memcpy中使用strchr

时间:2016-02-04 11:51:33

标签: c string substring memcpy strchr

我正在尝试将一个简单的代码示例(我可以在其中创建一个子字符串)转换为新的字符串。

我的代码如下:

char titulo[20];
char line[] = "PRINCIPAL,1.Liga,2.Clubes,3.Jogadores,4.Relatorios,5.Sair;";
char *pos = strchr(line,',');

memcpy(titulo, line,*pos);

问题在于,当我这样做时:

printf("%s",titulo);

我得到类似的东西:

  

本金,1.Liga,2.Clubes,3.Jogadores,4.Rela

1 个答案:

答案 0 :(得分:2)

因为你需要 null 终止titulo。实施例

char line[] = "PRINCIPAL,1.Liga,2.Clubes,3.Jogadores,4.Relatorios,5.Sair;";
char *pointer = strchr(line, ',');
if (pointer != NULL)
{
    char *substr;
    size_t length;
    length = pointer - line;
    /* Perhaps check if `length == 0', but it doesn't matter
     * because you would end up with an empty but valid sub string
     * anyway.
     */
    substr = malloc(length + 1);
    if (substr != NULL)
    {
        memcpy(substr, line, length);
        substr[length] = '\0';
        /* Use `substr' here */
        printf("%s\n", substr);
        /* Don't forget to free */
        free(substr);
    }
}