程序中使用的范围for需要编译器支持c++11
#include<iostream>
#include<string>
#include<vector>
using namespace std;
string strip(const string &str,char ch=' ')
{
//除去str两端的ch字符
int i = 0;
while (str[i] == ch)// 头部ch字符个数是 i
i++;
int j = str.size() - 1;
while (str[j] == ch ) //
j--;
return str.substr(i, j+1 -i );
}
vector<string> split(const string &str, string ch = " ")
{
//以 ch 为分割字符,把 cstr 分割为多个元素存到vector
vector<string>ret;
int pos = 0;
int start = 0;
while ((pos = str.find(ch, start) )!= string::npos )
{
//cout << "pos:" << pos << endl;
if (pos>start)
ret.push_back(str.substr(start, pos-start));
start = pos+ch.size();
}
if (str.size()>start)
ret.push_back(str.substr(start));
return ret;
}
int main()
{
string str = ".. first .. second .. third ..";
for (string str : split(str,".")) //单个字符
cout << "-" << str << "-" << endl;
for (string str : split(str,"..") ) //多个字符
cout << "-" << str <<"-"<<endl;
for (string str : split(str)) //默认用空格分割
cout << "-" << str << "-" << endl;
cout << "strip():" << strip(str,'.') <<"-"<< endl;
return 0;
}
vs2013运行结果: