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

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

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

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

参数说明:

  • str:要分割的字符串。在第一次调用时传入待分割的字符串,之后传入NULL,表示继续分割剩余的部分。
  • delim:分隔符字符串,用于指定分隔子字符串的字符。
  • context:保存上下文信息的指针,用于在多次调用strtok_s时保持状态。

返回值:

  • 如果成功找到下一个子字符串,则返回该子字符串的指针。
  • 如果没有找到下一个子字符串,则返回NULL。

下面是一个示例代码,展示了如何使用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会直接在原字符串上进行修改。

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百口可乐__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值