strtok()函数之谜
Mystery about strtok() function
很抱歉问了一个愚蠢的问题,但在阅读了大量示例后,我仍然不明白 strtok()
是如何工作的。
示例如下:
char s[] = " 1 2 3"; // 3 spaces before 1
int count = 0;
char* token = strtok(s, " ");
while (token != NULL) {
count++;
token = strtok(NULL, " ");
}
执行后count
等于3,为什么?
请解释我已经给出了调用该函数内部发生的事情的详细步骤。
它是 C,但 C++ 参考有一个很好的例子:http://www.cplusplus.com/reference/cstring/strtok/
char s[]
初始化后,指向包含数据的内存位置:1 2 3
.
第一次调用 strtok
,使用单个分隔符 space,将指针指向进一步的内存位置,现在只有:1 2 3
。进一步调用增加指针,指向连续标记的位置。
注意:将 strtok()
视为标记器函数,通过有效标记向前迭代。此外,打印出 pch
的当前值可能有助于更好地理解它(或使用调试器)。
因为:
http://man7.org/linux/man-pages/man3/strtok.3.html
From the above description, it follows that a sequence of two or more
contiguous delimiter bytes in the parsed string is considered to be a
single delimiter, and that delimiter bytes at the start or end of the
string are ignored.
您也可以打印连续的标记。
我的输出:
1个
2个
3
很抱歉问了一个愚蠢的问题,但在阅读了大量示例后,我仍然不明白 strtok()
是如何工作的。
示例如下:
char s[] = " 1 2 3"; // 3 spaces before 1
int count = 0;
char* token = strtok(s, " ");
while (token != NULL) {
count++;
token = strtok(NULL, " ");
}
执行后count
等于3,为什么?
请解释我已经给出了调用该函数内部发生的事情的详细步骤。
它是 C,但 C++ 参考有一个很好的例子:http://www.cplusplus.com/reference/cstring/strtok/
char s[]
初始化后,指向包含数据的内存位置:1 2 3
.
第一次调用 strtok
,使用单个分隔符 space,将指针指向进一步的内存位置,现在只有:1 2 3
。进一步调用增加指针,指向连续标记的位置。
注意:将 strtok()
视为标记器函数,通过有效标记向前迭代。此外,打印出 pch
的当前值可能有助于更好地理解它(或使用调试器)。
因为:
http://man7.org/linux/man-pages/man3/strtok.3.html
From the above description, it follows that a sequence of two or more
contiguous delimiter bytes in the parsed string is considered to be a
single delimiter, and that delimiter bytes at the start or end of the
string are ignored.
您也可以打印连续的标记。 我的输出: 1个 2个 3