C++标准库中的`strtok`函数是一个用于分割字符串的函数,它的原型如下:
```cpp
char *strtok(char *str
const char *delim);
```
`strtok`函数将字符串`str`按照分隔符`delim`进行分割,返回分割后的子字符串。在*次调用时,`str`应为要分割的字符串,之后调用时将`str`设置为`NULL`,函数将持续返回下一个子字符串直到所有子字符串都被分割完毕。
以下是一个示例代码,演示了如何使用`strtok`函数来分割字符串:
```cpp
#include #include int main() { char str[] = "Hello world this is a test"; const char delim[2] = " "; // 分隔符为逗号 char *token = strtok(str delim); // *次调用需要传入被分割的字符串 while (token != NULL) { std::cout < token="">< std::endl;=""> token = strtok(NULL delim); // 后续调用传入NULL即可 } return 0; } ``` 在上面的示例中,字符串`"Hello world this is a test"`被分割成了五个子字符串,分别是`"Hello"` `"world"` `"this"` `"is"` `"a"` `"test"`。逗号` `是作为分隔符传入`strtok`函数的,所以`strtok`函数会根据逗号来分割字符串。 需要注意的是,`strtok`函数会修改原始字符串,所以在调用`strtok`函数之前*将原始字符串复制一份保留。此外,`strtok`函数不是线程安全的,应尽量避免在多线程环境下使用。
咨询微信客服
0516-6662 4183
立即获取方案或咨询top