【发布时间】:2015-03-13 19:44:05
【问题描述】:
我正在使用was posted as an answer on another Stackoverflow question 的函数。然而,发布此消息的用户指出:it does not handle consecutive delimiters。
我想知道如何修改它以便它可以处理连续的分隔符?当我有一个额外的分界符时,我想基本上忽略它。
例如说我有这样的事情:
h2,3 d3,4 j3,3 y4,1 g4,3
我想在每个空格处将其拆分为一个字符串数组,但是您可以看到在某些情况下有多个空格。我只是想忽略额外的分隔符。
编辑:为了清楚起见,这是我在上面链接的答案中使用的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
char** str_split(char* a_str, const char a_delim)
{
char** result = 0;
size_t count = 0;
char* tmp = a_str;
char* last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char*) * count);
if (result)
{
size_t idx = 0;
char* token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char months[] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
char** tokens;
printf("months=[%s]\n\n", months);
tokens = str_split(months, ',');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("month=[%s]\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}
【问题讨论】:
-
忽略可能不是正确的方法,具体取决于具体情况。两个连续的分隔符只表示它们之间有一个空字符串。
-
@Havenard 这就是
strsep()的不同之处?使用适当的功能。