如何在C中拆分strtok字符串?

时间:2019-05-23 06:57:19

标签: c strtok

我扫描了一个文本文件,并使用strtok分割了字符串。分隔符是所有标点符号。我现在想取消拆分文件,以使其恢复到原始状态。有没有办法做到这一点?还是我应该再次加载文件?

1 个答案:

答案 0 :(得分:0)

对于单个定界符

char *unsplit(char *buff, char **argv, size_t size, int delimiter)
{
    size_t pos = 0;

    for (size_t index; index < size; index++)
    {
        strcpy(buff + pos, argv[index]);
        pos += strlen(argv[index]);
        if(index != size - 1) 
        {
            buff[pos++] = delimiter;
            buff[pos] = 0;
        }
    }
    return buff;
}

char *unsplitNULL(char *buff, char **argv, int delimiter)
{
    size_t pos = 0;

    while(*argv)
    {
        strcpy(buff + pos, *argv);
        pos += strlen(*argv++);
        if(*argv) 
        {
            buff[pos++] = delimiter;
            buff[pos] = 0;
        }
    }
    return buff;
}

int main()
{

    char *str[] = {"3443", "erte", "sdfdsffd", "wewere", NULL};
    char buff[100];
    printf("%s\n", unsplit(buff, str, 4, ','));
    printf("%s\n", unsplitNULL(buff, str, ','));

    return 0;
}