是否有strsep()的windows变种

时间:2011-12-14 22:57:41

标签: c windows

我试图解析一个带有一些空参数的分隔字符串。示例:

"|One|two|three||octopus|garbagecan||cartwheel||||"

基本上我需要能够通过id提取任何细分,如果细分为空,则返回null

strtok不处理空字段,看起来基于* nix的系统有strsep()。任何人都知道Windows是否有类似的东西?我想尽量避免写一个函数来处理这个问题。

3 个答案:

答案 0 :(得分:11)

只需使用其描述编写函数,它就不是非常复杂:

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

char* mystrsep(char** stringp, const char* delim)
{
  char* start = *stringp;
  char* p;

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

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

  return start;
}

// Test adapted from http://www.gnu.org/s/hello/manual/libc/Finding-Tokens-in-a-String.html.

int main(void)
{
  char string[] = "words separated by spaces -- and, punctuation!";
  const char delimiters[] = " .,;:!-";
  char* running;
  char* token;

#define PRINT_TOKEN() \
  printf("token: [%s]\n", (token != NULL) ? token : "NULL")

  running = string;
  token = mystrsep(&running, delimiters); /* token => "words" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "separated" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "by" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "spaces" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "and" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "punctuation" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => "" */
  PRINT_TOKEN();
  token = mystrsep(&running, delimiters); /* token => NULL */
  PRINT_TOKEN();

  return 0;
}

答案 1 :(得分:3)

我之前使用的http://unixpapa.com/incnote/string.html位置有一个公共域strsep()实施。但它需要strcspn(),这是你可能没有的C90功能。

答案 2 :(得分:2)

Gnu有一些glibc functions to windows

的端口