c++ 分割字符串的方法
c++ 中把string根据特殊符号分割字符串 ,类似java中的split写法
#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;
}
运行结果

来源://作者:/更新时间:2014-03-25
顶
踩
相关文章:
- c++ vector函数说明在最前面插入数据
- c++从内存中读取文件内容,内容写到内存 实现文件的内存
- 解决cgiMain.o(.text+0x8d): In function `main': :
- c/c++语言sprintf函数使用详解
- c/c++ 占位符使用及说明
- grails the action accept a parmeter of type which
- java中处理json数据方法_ jsonobject使用详解
- (解决)定义了重复的“system.web.extensions/scriptin
- python SyntaxError: Non-ASCII character '\xe6'
- error no 'server' jvm at 'C:\..\jre6\bin\jv

![1.2 变量和数据类型 (Variables and Data types )[C++基础教程]](/d/file/bianchengyuyan/cyuyan/2012-11-07/788bac7213da0c4bb727d0ea8a578297.png)