C++字符串分割strtok
2014-06-12 21:54
393 查看
字符串分割(C++)
经常碰到字符串分割的问题,这里总结下,也方便我以后使用。一、用strtok函数进行字符串分割原型: char *strtok(char *str, const char *delim);功能:分解字符串为一组字符串。参数说明:str为要分解的字符串,delim为分隔符字符串。返回值:从str开头开始的一个个被分割的串。当没有被分割的串时则返回NULL。示例:1 //借助strtok实现split 2 #include <string.h> 3 #include <stdio.h> 4 5 int main() 6 { 7 char s[] = "Golden Global View,disk * desk"; 8 const char *d = " ,*"; 9 char *p; 10 p = strtok(s,d); 11 while(p) 12 { 13 printf("%s\n",p); 14 p=strtok(NULL,d); 15 } 16 17 return 0; 18 }运行效果: 二、用STL进行字符串的分割 涉及到string类的两个函数find和substr:1、find函数原型:size_t find ( const string& str, size_t pos = 0 ) const;功能:查找子字符串第一次出现的位置。参数说明:str为子字符串,pos为初始查找位置。返回值:找到的话返回第一次出现的位置,否则返回string::npos 2、substr函数原型:string substr ( size_t pos = 0, size_t n = npos ) const;功能:获得子字符串。参数说明:pos为起始位置(默认为0),n为结束位置(默认为npos)返回值:子字符串 实现如下:
1 //字符串分割函数 2 std::vector<std::string> split(std::string str,std::string pattern) 3 { 4 std::string::size_type pos; 5 std::vector<std::string> result; 6 str+=pattern;//扩展字符串以方便操作 7 int size=str.size(); 8 9 for(int i=0; i<size; i++) 10 { 11 pos=str.find(pattern,i); 12 if(pos<size) 13 { 14 std::string s=str.substr(i,pos-i); 15 result.push_back(s); 16 i=pos+pattern.size()-1; 17 } 18 } 19 return result; 20 }完整代码:View Code运行效果:三、用Boost进行字符串的分割用boost库的正则表达式实现字符串分割实现如下:
1 std::vector<std::string> split(std::string str,std::string s) 2 { 3 boost::regex reg(s.c_str()); 4 std::vector<std::string> vec; 5 boost::sregex_token_iterator it(str.begin(),str.end(),reg,-1); 6 boost::sregex_token_iterator end; 7 while(it!=end) 8 { 9 vec.push_back(*it++); 10 } 11 return vec; 12 }完整代码:View Code运行效果:补充:最近发现boost里面有自带的split的函数,如果用boost的话,还是直接用split的好,这里就不多说了,代码如下:
#include <iostream> #include <string> #include <vector> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> using namespace std; int main() { string s = "sss/ddd,ggg"; vector<string> vStr; boost::split( vStr, s, boost::is_any_of( ",/" ), boost::token_compress_on ); for( vector<string>::iterator it = vStr.begin(); it != vStr.end(); ++ it ) cout << *it << endl; return 0; }
http://www.cnblogs.com/MikeZhang/archive/2012/03/24/MySplitFunCPP.html
http://blog.csdn.net/mycwq/article/details/14648011
相关文章推荐
- c++ 字符串分割一、用strtok函数进行字符串分割 原型: char *strtok(char *str, const char *delim); 功能:分解字符串为一组字符串。 参数说明:
- C/C++如何把一个特定分隔符分割的字符串划分为一个字符串数组,strtok(char *,char*)分割函数
- c++中怎么分割字符串之strtok 函数
- 【C++】字符串分割 strtok_s
- c++分割字符串,strtok与strtok_r的使用记录
- C++组合应用之strtok字符串分割、数组平分算法、动态数组函数传参
- C/C++分割字符串:strtok函数
- c/c++ 字符串分割 (strtok)
- [C++] strtok 分割字符串函数
- 分割字符串:strtok()函数
- C++字符串处理(重写)trcpy、strlen、strcat、strcmp、strlwr、strupr、strrev、strchr、strpbrk、strstr、strtok
- 标准C++ 与MFC 6.0 中字符串的分割
- strtok是分割字符串,查找中间最长的单元
- C++分割字符串的类
- 有关strtok函数进行字符串分割
- C字符串分割 - strtok 与 strtok_r
- C分割字符串 sscanf vs strtok
- C语言中strtok函数进行分割字符串!
- c++ 字符串分割
- strtok(分割字符串)