C 中的字符串分词器
下面的代码将使用空格(即“”)和句号(即“”)来分解字符串命令。如果我想使用空格和句号的出现(同时)而不是单独使用它们来分解命令,例如:“hello .how are you”将被分解为多个片段(忽略引号) [你好] [你今天怎么样]
char *token2 = strtok(command, " .");
the following code will break down the string command using space i.e " " and a full stop i.e. "." What if i want to break down command using the occurrence of both the space and full stop (at the same time) and not each by themselves e.g. a command like: 'hello .how are you' will be broken into the pieces (ignoring the quotes)
[hello]
[how are you today]
char *token2 = strtok(command, " .");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
strstr
轻松完成此操作:这与
strtok
的实现几乎完全相同,只需调用strstr
和strlen
而不是strcspn
和strspn
。它还可能返回空标记(如果有两个连续的分隔符或两端各有一个分隔符);如果您愿意,可以安排忽略这些内容。You can do it pretty easily with
strstr
:This is pretty much exactly the same as the implementation of
strtok
, just callingstrstr
andstrlen
instead ofstrcspn
andstrspn
. It also might return empty tokens (if there are two consecutive delimiters or a delimiter at either end); you can arrange to ignore those if you would prefer.您最好的选择可能就是使用
strstr
抓取您的输入,它会查找子字符串的出现,并手动对这些子字符串进行标记。这是您提出的一个常见问题,但我还没有看到特别优雅的解决方案。然而,上述内容是简单且可行的。
Your best bet might just be to crawl your input with
strstr
, which finds occurrences of a substring, and manually tokenize on those.It's a common question you ask, but I've yet to see a particularly elegant solution. The above is straightforward and workable, however.