String tokenizer in c

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 03:13:06

问题


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

回答1:


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

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.




回答2:


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.



来源:https://stackoverflow.com/questions/7136528/string-tokenizer-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!