c++中strtok函数的用法是什么

2024-04-23

在C++中,strtok函数用于将字符串按照指定的分隔符进行分割。其基本用法如下:

char *strtok(char *str, const char *delim);

其中,str是要分割的字符串,delim是分隔符,可以是一个字符串,也可以是多个字符。该函数会返回被分割出的子字符串,并在后续调用时继续返回下一个子字符串。

示例代码如下:

#include <iostream>
#include <cstring>

int main() {
    char str[] = "hello,world;how are you";
    char *token = std::strtok(str, ",;");

    while (token != nullptr) {
        std::cout << token << std::endl;
        token = std::strtok(nullptr, ",;");
    }

    return 0;
}

在上面的例子中,我们将字符串"hello,world;how are you"按照逗号和分号进行分割,并输出分割后的子字符串。

《c++中strtok函数的用法是什么.doc》

下载本文的Word格式文档,以方便收藏与打印。