C++string 分割
来源:互联网 发布:淘宝其他店铺流量来源 编辑:程序博客网 时间:2024/06/07 11:23
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;}
0 0
- C++string 分割
- [C++]string分割字符串
- (C#)重写分隔符分割字符串 - string.Split(char[] separator)
- How to split string in C++(分割字符串)
- C++ String类
- 【poj 1191】棋盘分割 题解&代码(C++)
- 【apio2014】【bzoj3675】序列分割 题解&代码(C++)
- C#String.Split (string[], StringSplitOptions) 多参数分割得到数组
- String分割方法总结
- string中文分割
- C++ string 分割字符
- <笔记>如何分割string
- c++中的string分割
- String 分割(备忘)
- String的分割
- string 字符串分割
- String.split() 字符串分割
- C++ string 分割字符
- Android listView同时展示多种不同数据的item
- linux文件系统变为只读的修复
- 浏览器渲染原理
- Interleaving String
- Android中Application类用法
- C++string 分割
- Android系统启动流程
- Swift调用C/C++/OC语言桥接文件命名规则
- boost bind 实现方法
- Android Jni/Linux APP层和kernel层延时
- OAuth的机制原理讲解及开发流程
- 62 Unique Paths
- 安卓中的Flux架构
- gcc的 -Wl参数的作用