简体   繁体   English

具有连续定界符的strtok_s行为

[英]strtok_s behaviour with consecutive delimiters

I'm parsing 3 values in parallel which are separated with a specific separator. 我正在并行解析3个值,这些值用特定的分隔符分隔。

token1 = strtok_s(str1, separator, &nextToken1);
token2 = strtok_s(str2, separator, &nextToken2);
token3 = strtok_s(str3, separator, &nextToken3);

while ((token1 != NULL) && (token2 != NULL) && (token3 != NULL))
{
    //...
    token1 = strtok_s(NULL, separator, &nextToken1);
    token2 = strtok_s(NULL, separator, &nextToken2);
    token3 = strtok_s(NULL, separator, &nextToken3);
}

Suppose '-' is my separator. 假设“-”是我的分隔符。 The behaviour is that a string with no consecutive separators: 行为是没有连续分隔符的字符串:

1-2-3-45

would effectively result in each of these parts: 将有效地导致以下各个方面:

1
2
3
45

However, a string with two consecutive separators: 但是,具有两个连续分隔符的字符串:

1-2--3-45

will not yield a 0 length string, that one is skipped so that the result is: 不会产生长度为0的字符串,该字符串将被跳过,结果是:

1
2
3
45

and not 并不是

1
2

3
45

What workaround or strategy would be better suited to obtain all the actual parts, including the 0-length ones? 哪种解决方法或策略更适合于获取所有实际零件,包括长度为0的零件? I'd like to avoid re-implementing strtok_s, if possible. 如果可能的话,我想避免重新实现strtok_s。

Unfortunately, strtok() ignores empty tokens. 不幸的是, strtok()忽略了空令牌。 Even though you said you wish to avoid doing that, there is no other way but to parse it yourself, using for example strchr() to find the next delimiter and then copying the token to a temporary variable for processing. 即使您说希望避免这样做,也只能通过自己解析它,例如使用strchr()查找下一个定界符,然后将令牌复制到一个临时变量中进行处理,就没有其他方法了。 This way you can handle empty tokens whichever way you please. 这样,您可以随心所欲地处理空令牌。

Yes, that's the way this function works. 是的,这就是该功能的工作方式。 It's more appropriate for tasks like parsing words where multiple whitespace characters should not be treated as empty words. 它更适合诸如单词解析之类的任务,其中多个空格字符不应被视为空单词。

I've done a lot of parsing. 我已经做了很多解析。 I would simply write my own parser here, where the code examines one character at a time. 我只是在这里编写自己的解析器,其中代码一次检查一个字符。 It's not that difficult and you can make it behave exactly how you need. 这并不困难,您可以使其表现出所需的功能。 As an example, I've posted some C++ code to parse a CSV file in my article Reading and Writing CSV Files in MFC 作为示例,我在文章“在MFC中读写CSV文件”中发布了一些C ++代码来解析CSV文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM