strtok


原型

char* strtok(char* s,const char* delim)


功能

分解字符串为一组字符串,s为要分解的字符串,delim为分隔符字符串,当在参数s 的字符串中发现到字符串delim 时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s 字符串,往后的调用则将参数s 设置成NULL。每次调用成功则返回下一个分割后的字符串指针


返回值

若str2是str1的子串,则返回str2在str1的首次出现的地址
如果str2不是str1的子串,则返回NULL


示例

#include <string.h>
#include <iostream.h>
void main(void)
{
    char input[100]="abc,d,ef,ghi,jk,lmno";
    int i=0;
    char *p = input;
 
    while ((p=strtok(p,",")) != NULL)
    {
        i++;
        cout<<"split str"<<i<<":"<<p<<endl;
        p = NULL;
    }

    cout<<"input:"<<input<<endl;
}

结果:
split str1:abc
split str2:d
split str3:ef
split str4:ghi
split str5:jk
split str6:lmno
input:abc


注意

该函会破坏被分解字符串的完整,由上面的例子可看出,input在调用前后已经不一样了。


strtok_s

strtok_s是windows下的一个分割字符串安全函数,函数原型:
char *strtok_s( char *strToken, const char *strDelimit, char **buf);
这个函数将剩余的字符串存储在buf变量中,而不是静态变量中,从而保证了安全性。

strtok_r

strtok_s函数是linux下分割字符串的安全函数,函数 原型
char *strtok_r(char *str, const char *delim, char **saveptr);


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值