分割字符串

The strtok() function parses a string into a sequence  of  tokens.   On
       the  first call to strtok() the string to be parsed should be specified
       in str.  In each subsequent call that should parse the same string, str

       should be NULL.

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char sentence[]="This is a sentence with 7 tokens";
cout<<"The string to be tokenized is:\n"<<sentence<<"\n\nThe tokens are:\n\n";
char *tokenPtr=strtok(sentence," ");
while(tokenPtr!=NULL)
{
cout<<tokenPtr<<'\n';
tokenPtr=strtok(NULL," ");
}
//cout<<"After strtok, sentence = "<<tokenPtr<<endl;
return 0;
}

函数第一次调用需设置两个参数。第一次分割的结果,返回串中第一个 ',' 之前的字符串,也就是上面的程序第一次输出abc。
第二次调用该函数strtok(NULL,","),第一个参数设置为NULL。结果返回分割依据后面的字串,即第二次输出d。
strtok是一个线程不安全的函数,因为它使用了 静态分配的空间来存储被分割的字符串位置
线程安全的函数叫strtok_r,ca
运用strtok来判断ip或者mac的时候务必要先用其他的方法判断'.'或':'的个数,因为用strtok截断的话,比如:"192..168.0...8..."这个字符串,strtok只会截取四次,中间的...无论多少都会被当作一个key


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值