C++的字符串分割函数
2015-06-06 23:06
435 查看
转载:/article/2841560.html
C++的字符串没有分割函数,因此需要自己写方便使用。而受到开发工具的影响,有很多用起来比较麻烦啦,下面这个比较不错奥。
用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)
返回值:子字符串
实现如下:
C++的字符串没有分割函数,因此需要自己写方便使用。而受到开发工具的影响,有很多用起来比较麻烦啦,下面这个比较不错奥。
用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)
返回值:子字符串
实现如下:
/* File : split1.cpp Author : Mike E-Mail : Mike_Zhang@live.com */ #include <iostream> #include <string> #include <vector> //字符串分割函数 std::vector<std::string> split(std::string str,std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str+=pattern;//扩展字符串以方便操作 int size=str.size(); for(int i=0; i<size; i++) { pos=str.find(pattern,i); if(pos<size) { std::string s=str.substr(i,pos-i); result.push_back(s); i=pos+pattern.size()-1; } } return result; } int main() { std::string str; std::cout<<"Please input str:"<<std::endl; //std::cin>>str; getline(std::cin,str); std::string pattern; std::cout<<"Please input pattern:"<<std::endl; //std::cin>>pattern; getline(std::cin,pattern);//用于获取含空格的字符串 std::vector<std::string> result=split(str,pattern); std::cout<<"The result:"<<std::endl; for(int i=0; i<result.size(); i++) { std::cout<<result[i]<<std::endl; } std::cin.get(); std::cin.get(); return 0; }
相关文章推荐
- c++读取文件–结束条件的判断
- C语言 变量作为函数定义中的实参写法
- C++ 容器及选用总结
- c++对象模型
- c++拷贝构造函数
- c++拷贝构造函数
- 归并排序、插入排序、快速排序、二分查找的c++实现
- 黑马程序员——OC语言基础——面向对象三大特性之封装
- rand()和srand()函数
- 流类库与输入输出--精度
- C++:cin、cin.getline()、getline()的用法
- C++实现带路径记录的Floyd-Warshall算法
- chapter11test2
- C++怎么把整型、浮点型、字符串格式化输出到一个字符串中
- C++实现floyd-warshall算法
- 【学习笔记】【C语言】关系运算符
- 我们来谈谈C++里面的字符串
- C语言第一天 环境配置 QT与XCode安装
- chapter11test1
- 其他进制转十进制(C++)