Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

c - Is there a Windows variant of strsep() function?

I'm trying to parse a delimited string that has some empty parameters.

Example:

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

Basically I need to be able to pull out any segment by id, and if the segment is empty return null.

strtok() doesn't handle the empty fields, and it looks like there is strsep() for *nix based systems. Anyone know if there is something similar for Windows? I want to try and avoid having to write a function to handle this if I can.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just write the function using its description, it's not terribly complex:

#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 = '';
    *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]
", (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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...