c语言字符串分割函数strtok_s和strtok

⌚Time: 2024-01-19 20:22:09

👨‍💻Author: Jack Ge

strtok_sstrtok是C语言提供的字符串分割函数,用于将一个字符串按照指定的分隔符进行分割成多个子字符串。

strtok_s是C11标准库中提供的安全版本的字符串分割函数,其基本语法如下:


char* strtok_s(char* str, const char* delim, char** context);

参数说明:

返回值:

下面是一个示例代码,展示了如何使用strtok_s函数进行字符串分割:


#include <iostream>

#include <cstring>



int main() {

    char str[] = "apple,banana,cherry";

    char* token = nullptr;

    char* nextToken = nullptr;

    const char* delim = ",";



    token = strtok_s(str, delim, &nextToken);

    while (token != nullptr) {

        std::cout << token << std::endl;

        token = strtok_s(nullptr, delim, &nextToken);

    }



    return 0;

}

在这个示例中,我们将字符串"apple,banana,cherry"按照逗号分隔符进行分割,并逐个打印出分割后的子字符串。我们使用strtok_s函数进行分割,初始时将待分割的字符串传入,后续传入NULL表示继续分割剩余部分。当strtok_s返回NULL时,表示已经没有更多的子字符串需要分割。

需要注意的是,strtok_s是C11标准引入的函数,可能在一些旧的编译器或平台上不支持。在这种情况下,可以使用strtok函数,其基本用法与strtok_s类似,但没有安全性保证。使用strtok时,需要注意在多次调用中传入NULL来继续分割字符串,并且需要在每次调用之间保存上下文信息。


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

示例代码:


#include <iostream>

#include <cstring>



int main() {

    char str[] = "apple,banana,cherry";

    char* token = nullptr;

    const char* delim = ",";



    token = strtok(str, delim);

    while (token != nullptr) {

        std::cout << token << std::endl;

        token = strtok(nullptr, delim);

    }



    return 0;

}

注意,使用strtok时需要小心处理原字符串的内容,因为strtok会直接在原字符串上进行修改。