0

我想通过';'将字符串拆分为标记。但是我有一个问题,例如某些令牌是空的/空的;123;123132;;;232;232323;;;;1; 所以我不能使用 strtok 因为合并相邻分隔符。我看到你发布了这个解决方案:

include <string.h>

char *data = "this&&that&other";
char *next;
char *curr = data;
while ((next = strchr(curr, '&')) != NULL) {
    /* process curr to next-1 */
    curr = next + 1;
}
/* process the remaining string (the last token) */

但我不明白,因为当我执行 next-1 以获得第一个值时,我只得到值的第一个单词,而不是整个值。你能帮我吗?,你知道如何分割这个吗?我在 C ansi 编程。我在另一篇文章中看到存在一个 strsep 函数,这似乎正是我需要的,但在 C ansi 库中不包含此函数。谢谢和对不起我的英语:)

4

2 回答 2

0

我认为这是你想要的:-

#include <stddef.h>
#include <string.h>
#include <stdio.h>

char* mystrsep(char** input, const char* delim)
{
  char* result = *input;
  char* p;

  p = (result != NULL) ? strpbrk(result, delim) : NULL;

  if (p == NULL)
    *input = NULL;
  else
  {
    *p = '\0';
    *input = p + 1;
  }

  return result;
}

int main()
{
  char str[] = "123;123132;;;232;232323;;;;1;";
  const char delimiters[] = ";";
  char* ptr;
  char* token;

    ptr = str;
  token = mystrsep(&ptr, delimiters);
  while(token)
    {
      printf("%s\n",token);
       token = mystrsep(&ptr, delimiters);
    }   
  return 0;
}
于 2013-08-01T12:00:19.627 回答
0
#include <stdio.h>
#include <string.h>

char *strtok_r_noskip(char *str, const char *delims, char **store){
    char *p, *wk;
    if(str != NULL){
        *store = str;
    }
    if(*store == NULL) return NULL;
    //*store += strspn(*store, delims);//skip delimiter
    if(**store == '\0') return NULL;
    p=strpbrk(wk=*store, delims);
    if(p != NULL){
        *p='\0';
        *store = p + 1;
    } else {
        *store = NULL;
    }
    return wk;
}


int main(void){
    char data1[] = "this&&that&other";
    char *store, *token = strtok_r_noskip(data1, "&", &store);
    for(; token ; token = strtok_r_noskip(NULL, "&", &store)) {
        printf("\"%s\"\n", token);
    }
/* output
"this"
""
"that"
"other"
*/
    char data2[] = "123;123132;;;232;232323;;;;1;";
    token = strtok_r_noskip(data2, ";", &store);
    for(; token ; token = strtok_r_noskip(NULL, ";", &store)) {
        printf("\"%s\"\n", token);
    }
/* output
"123"
"123132"
""
""
"232"
"232323"
""
""
""
"1"
*/

   return 0;
}
于 2013-08-01T14:09:50.487 回答