字符串tokenizer在c [英] String tokenizer in c

查看:178
本文介绍了字符串tokenizer在c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将使用空格(即和完整止损(即))分隔字符串命令。如果我想分解命令使用空间和全停止(同时)的出现,而不是每个自己例如。命令如下:'hello。你是你'将被分成片断(忽略引号)
[hello]
[今天你是什么]

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, " .");


推荐答案

c> strstr :

You can do it pretty easily with strstr:

char *strstrtok(char *str, char *delim)
{
    static char *prev;
    if (!str) str = prev;
    if (str) {
        char *end = strstr(str, delim);
        if (end) {
            prev = end + strlen(delim);
            *end = 0;
        } else {
            prev = 0;
        }
    }
    return str;
}

这实际上与 strtok ,只需调用 strstr strlen ,而不是 strcspn strspn 。它也可能返回空令牌(如果有两个连续的分隔符或在任一端的分隔符);你可以安排忽略这些,如果你愿意。

This is pretty much exactly the same as the implementation of strtok, just calling strstr and strlen instead of strcspn and strspn. 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.

这篇关于字符串tokenizer在c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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