在C中,如何将\ n上的字符串拆分为行

时间:2013-08-25 13:01:51

标签: c split strtok

我希望用\n拆分字符串,并将包含特定标记的行放入数组中。

我有这段代码:

char mydata[100] = 
    "mary likes apples\njim likes playing\nmark hates school\nanne likes mary";
char *token = "likes";
char ** res  = NULL;
char * p = strtok (mydata, "\n");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
    res = realloc (res, sizeof (char*) * ++n_spaces);
    if (res == NULL)
    exit (-1); /* memory allocation failed */
    if (strstr(p, token))
        res[n_spaces-1] = p;
    p = strtok (NULL, "\n");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = '\0';
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
    printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);

但后来我遇到了分段错误:

res[0] = mary likes apples
res[1] = jim likes playing
Segmentation fault

如何在C中正确分割\n上的字符串?

2 个答案:

答案 0 :(得分:1)

试试这个:

char mydata[100] = "mary likes apples\njim likes playing\nmark hates school\nanne likes mary";
char *token = "likes";
char **result = NULL;
int count = 0;
int i;
char *pch;

// split
pch = strtok (mydata,"\n");
while (pch != NULL)
{
    if (strstr(pch, token) != NULL)
    {
        result = (char*)realloc(result, sizeof(char*)*(count+1));
        result[count] = (char*)malloc(strlen(pch)+1);
        strcpy(result[count], pch);
        count++;
    }
    pch = strtok (NULL, "\n");
}

// show and free result
printf("%d results:\n",count);
for (i = 0; i < count; ++i)
{
    printf ("result[%d] = %s\n", i, result[i]);
    free(result[i]);
}
free(result);

答案 1 :(得分:1)

strstr只返回指向第二个参数的第一个匹配的指针。

您的代码没有处理空字符。

可以使用strcpy复制字符串。

while (p) {
  // Also you want string only if it contains "likes"

    if (strstr(p, token))
    {
        res = realloc (res, sizeof (char*) * ++n_spaces);
        if (res == NULL)
          exit (-1); 
        res[n_spaces-1] = malloc(sizeof(char)*strlen(p));

        strcpy(res[n_spaces-1],p);
     }
    p = strtok (NULL, "\n");
}

免费res使用:

for(i = 0; i < n_spaces; i++)
    free(res[i]);
free(res);