是否有 strsep() 函数的 Windows 变体? [英] Is there a Windows variant of strsep() function?

查看:32
本文介绍了是否有 strsep() 函数的 Windows 变体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析一个带有一些参数的分隔字符串.

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

示例:

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

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

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

strtok() 不处理空字段,看起来像基于 *nix 的系统有 strsep() .有谁知道Windows是否有类似的东西?如果可以的话,我想尽量避免编写一个函数来处理这个问题.

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.

推荐答案

只需使用它的描述来编写函数,它并不复杂:

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 = '\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;
}

这篇关于是否有 strsep() 函数的 Windows 变体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆