stork_k函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010339647/article/details/79268413

stork_k函数

strtok_r()函数用于分割字符串。strtok_r是linux平台下的strtok函数的线程安全版。windows的string.h中并不包含它。

char *strtok_r(char *str, const char *delim, char **saveptr);
strtok_r函数是strtok函数的可重入版本。str为要分解的字符串,delim为分隔符字符串。char *saveptr参数是一个指向char 的指针变量,用来在strtok_r内部保存切分时的上下文,以应对连续调用分解相同源字符串。
第一次调用strtok_r时,str参数必须指向待提取的字符串,saveptr参数的值可以忽略。连续调用时,str赋值为NULL,saveptr为上次调用后返回的值,不要修改。一系列不同的字符串可能会同时连续调用strtok_r进行提取,要为不同的调用传递不同的saveptr参数。

  • 当delim在str中不存在时:

    • str!=”“;结果为str;
    • str=”“;结果为NULL;
#include "iostream"
#include <stdio.h>
#include "string.h"
using namespace std;

int main(){

    char *tmp = NULL;

    char str1[1024] = "123&abc";
    char str2[1024] = "123";

    char *tmp1 = NULL;
    char *tmp2 = NULL;

    const char *re1 = strtok_r(str1, DELIMIT3, &tmp1);
    const char *re2 = strtok_r(str2, DELIMIT3, &tmp2);

    if(re2 == NULL){
        cout<<"null"<<endl;;
    } else {
        cout<<"not null"<<endl;;
    }

    /*切分出123*/
    cout<<"str1 = "<<str1<<"  re1 = "<<re1<<" tmp1 = "<<tmp1<<"----"<<endl;
    cout<<"str2 = "<<str2<<"  re2 = "<<re2<<" tmp2 = "<<tmp2<<"----"<<endl;

    //运行到这个地方 tmp1="123" tmp2=""

    /*tmp1中不含有v,则直接返回abc*/
    re1 = strtok_r(NULL, "v", &tmp1);
    if(re1 == NULL){
        cout<<"null"<<endl;;
    } else {
        cout<<"not null re1 = "<<re1<<endl;;
    }

    if (tmp2 == NULL) {
        cout<<"tmp2 == NULL"<<endl;
    } else {
        cout<<"tmp2 != NULL"<<endl;
    }

    re2 = strtok_r(NULL, DELIMIT3, &tmp2);
    if(re2 == NULL){
        cout<<"null"<<endl;;
    } else {
        cout<<"not null"<<endl;;
    }
    return 0;
}

输出是:

not null
str1 = 123  re1 = 123 tmp1 = abc----
str2 = 123  re2 = 123 tmp2 = ----
not null re1 = abc
tmp2 != NULL
null

猜你喜欢

转载自blog.csdn.net/u010339647/article/details/79268413