C++ 中的 strtok()
函数返回 C 字符串(以 null 结尾的字节字符串)中的下一个标记。
“标记”是 字符串 的较小片段,它们由指定的字符(称为分隔符)分隔。
此函数定义在 cstring 头文件中。
示例
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char quote[] = "Remember me when you look at the moon!";
// break the string when it encounters empty space
char* word = strtok(quote, " ");
cout << word;
return 0;
}
// Output: Remember
strtok() 语法
strtok()
的语法是
strtok(char* str, const char* delim);
简单来说,
- str - 我们要从中获取标记的字符串
- delim - 分隔符字符,即分隔标记的字符
strtok() 参数
- str - 要标记的以 null 结尾的字节字符串(C 字符串)的指针
- delim - 包含分隔符的以 null 结尾的字节字符串的指针
strtok() 返回值
strtok()
函数返回
- 如果存在下一个标记,则返回指向该标记的指针
- 如果找不到更多标记,则返回
NULL
值
strtok() 声明
cstring 头文件中定义的 strtok()
函数的声明是
char* strtok(char* str, const char* delim);
strtok() 的多次调用
strtok()
可以被多次调用以从同一字符串中获取标记。有两种情况:
情况 1:str 不为 NULL
- 这是该字符串的第一次调用
strtok()
。 - 该函数搜索第一个不包含在 delim 中的字符。
- 如果找不到这样的字符,则该字符串不包含任何标记。因此,返回一个**空指针**。
- 如果找到这样的字符,那么从那里开始,函数将搜索一个存在于 delim 中的字符。
- 如果找不到分隔符,则 str 只有一个标记。
- 如果找到分隔符,则它将被替换为
'\0'
,并且指向后续字符的指针将存储在静态位置以供后续调用。
- 最后,函数返回指向标记开头的指针。
情况 2:str 为 NULL
- 此调用被视为 str 的后续
strtok()
调用。 - 函数从上一次调用结束的地方继续。
示例 1:C++ strtok()
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char quote[] = "Remember me when you look at the moon!";
// break the string when it encounters empty space
// str = quote, delim = " "
char* word = strtok(quote, " ");
cout << "token1 = " << word << endl;
// get the next token i.e. word before second empty space
// NULL indicates we are using the same pointer we used previously i.e. quote
word = strtok(NULL, " ");
cout << "token2 = " << word;
// get the third token
word = strtok(NULL, " ");
cout << "token3 = " << word;
return 0;
}
输出
token1 = Remember token2 = me token3 = when
在这个程序中,
- 我们使用空字符串
" "
作为分隔符 delim 对 quote C 字符串进行了标记。每次strtok()
遇到空格" "
时,这会将 quote 分割成标记。
- 第一次调用函数时,我们需要传递 quote 字符串,以指定它是源字符串参数 src。
char* word = strtok(quote, " ");
- 所有后续对
strtok()
函数的调用都将NULL
作为 src 参数。此参数指示编译器使用先前使用的 C 字符串指针(即 quote)作为源 src。
word = strtok(NULL, " ");
示例 2:打印字符串中的所有标记
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str[] = "Remember me when you look at the moon!";
char delim[] = " ";
cout << "The tokens are:" << endl;
// tokenize str in accordance with delim
char *token = strtok(str,delim);
// loop until strtok() returns NULL
while (token) {
// print token
cout << token << endl;
// take subsequent tokens
token = strtok(NULL,delim);
}
return 0;
}
输出
The tokens are: Remember me when you look at the moon!