Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 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 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...