简体   繁体   English

将正确的参数传递给 strtok

[英]Passing the right argument to strtok

I have this string that I'm trying to delimit with strtok() :我有这个字符串,我试图用strtok()分隔:

"+ 2 3\\nln 9\\ln 10" "+ 2 3\\nln 9\\ln 10"

And then I'm passing \\n as a delimiter然后我将\\n作为分隔符传递

    token = strtok(argv, "\\n");

    while (token)
    {
            args[index] = token;
            token = strtok(NULL, "\\n");
            index++;
    }

First element in my args table is + 2 3 ,which is great, however, the second one is l .我的args表中的第一个元素是+ 2 3 ,这很好,但是,第二个元素是l Does anyone understand why?有谁明白为什么? If so, how do I get my ln 9 in my args table?如果是这样,我如何在我的args表中获得我的ln 9

From strtok() manpage :strtok() manpage

The delim argument specifies a set of bytes that delimit the tokens in the parsed string. delim参数指定一组字节,用于分隔已解析字符串中的标记。 The caller may specify different strings in delim in successive calls that parse the same string.调用者可以在解析相同字符串的连续调用中在 delim 中指定不同的字符串。

So, in your code, "\\n" is not a full string delimiter.因此,在您的代码中, "\\n"不是完整的字符串分隔符。 You are just saying to strtok that the delimiter is either '\' (because of the double backspace escaping) or 'n' .您只是对strtok说分隔符'\' (因为双退格转义)'n'

The tokens of your string, "+ 2 3\\nln 9\\ln 10" will be:您的字符串标记"+ 2 3\\nln 9\\ln 10"将是:

  1. "+ 2 3"
  2. empty string between \ and \ (strtok doesn't present it) \\之间的空字符串(strtok 不显示它)
  3. empty between \ and n (strtok doesn't present it) \n之间为空(strtok 不显示)
  4. "l"
  5. " 9"
  6. empty string between \ and \ (strtok doesn't present it) \\之间的空字符串(strtok 不显示它)
  7. "l"
  8. " 10"

In order to perform what you are trying to do, strtok is not the best choice.为了执行您要执行的操作, strtok不是最佳选择。 I would probably write my own parsering function我可能会编写自己的解析 function

  1. Finding "\\n" occurrences in original string using strstr()使用strstr()在原始字符串中查找"\\n"次出现
  2. Either copying the previous string to some output string or null terminating it in place将前一个字符串复制到某个 output 字符串或 null 将其终止

I completely agree with above answer and suggestions by Roberto and Gerhardh.我完全同意 Roberto 和 Gerhardh 的上述回答和建议。

In case if you are fine with custom implementation of strtok for multiple delimeter, you can use below working solution.如果您对多分隔符的 strtok 的自定义实现感到满意,您可以使用以下工作解决方案。

char *strtokm(char *str, const char *delim)
{
    static char *tok;
    static char *next;
    char *m;

    if (delim == NULL) return NULL;

    tok = (str) ? str : next;
    if (tok == NULL) return NULL;

    m = strstr(tok, delim);

    if (m) {
        next = m + strlen(delim);
        *m = '\0';
    } else {
        next = NULL;
    }

    return tok;
}

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

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