strtok

char *strtok(char s[], const char *delim);
功能: 分解字符串为一组字符串。s为要分解的字符串,delim为 分隔符 字符串。
例如:strtok("abc,def,ghi",","),最后可以分割成为abc def ghi.尤其在点分十进制的IP中提取应用较多。

    4 strtok()用来将字符串分割成一个个片段。参数s指向欲分割的 字符 串,参数delim则为分割字符串中包含的所有字符。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时,则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串,往后的调用则将参数s设置成NULL。
每次调用成功则返回指向被分割出片段的 指针

所有delim中包含的字符都会被滤掉,并将被滤掉的地方设为一处分割的节点。从s开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。

5

strtok函数会破坏被分解字符串的完整,调用前和调用后的s已经不一样了。如果
要保持原字符串的完整,可以使用strchr和sscanf的组合等
#include <string.h>
#include <stdio.h>
int main()
{
    char input[16] = "abc,d";
    char *p;
    /* strtok places a NULL terminator
    in front of the token, if found */
    p = strtok(input, ",");
    if (p)
    {
        printf("%s\n", p);
    }
    /* A second call to strtok using a NULL
    as the first parameter returns a pointer
    to the character following the token */
    p = strtok(NULL, ",");
    if (p)
    {
        printf("%s\n", p);
    }

return 0;
}

以上是C语言代码,验证了上述函数原型,函数功能,返回值等说法
#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;
}

以上是C++代码,自然看得出来,strtok函数存在于#include<cstring>  #include<string.h>


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

6

#include<string.h>
#include<stdio.h>
int main()
{
    char input[16]="a,b,c,d";
    char *p;
    p=strtok(input,",");
    while(p)
    {
        printf("%s\n",p);
        p=strtok(NULL,",");
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值