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

来源:互联网 发布:math js w3c 编辑:程序博客网 时间:2024/05/29 10:09

原型:

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


作用:
分解字符串为一组字符串。s为要分解的字符串,delim为分隔符字符串。

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

返回值:

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


如下面的例子,可修改 seps里面的数据,然后看输出结果:

#include <string.h>#include <stdio.h>int main( void ){char buf[] = "A string\tof ,,tokens\nand some  more tokens";char seps[] = " ,\t\n"; printf( "%s\n\nTokens:\n", buf );/* Establish string and get the first token: */char *token = strtok( buf, seps );while( token != NULL ){/* While there are tokens in "buf" */printf( " %s\n", token );/* Get next token: */token = strtok( NULL, seps );}system("pause");return 0;}


稍作修改,可以封装一个用于字符串分割函数:

#include <string.h>#include <stdio.h>#include <vector>std::vector<char*> split_string(char buf[], char seps[]){std::vector<char*> result;char *token = strtok( buf, seps );if (token != NULL){result.push_back(token);}while( token != NULL ){/* Get next token: */token = strtok( NULL, seps );/* Append to array */if (token != NULL){result.push_back(token);}}return result;}int main( void ){char buf[] = "A string\tof ,,tokens\nand some  more tokens";char seps[] = " ,\t\n"; printf( "%s\n\nTokens:\n", buf );//std::vector<char*> data = split_string(buf, seps);for (int i=0; i<data.size(); ++i){printf( " %s\n", data[i] );}system("pause");return 0;}


输出结果与之前的一样:


0 0
原创粉丝点击