#include<string>
using namespace std;
字符串切割
int DataHelper::split( const string &str, vector<string> &result, const string &sep )
{
if (str.empty())
{
return 0;
}
string tmp;
string::size_type pos_begin = str.find_first_not_of(sep);
string::size_type comma_pos = 0;
while (pos_begin != string::npos)
{
comma_pos = str.find(sep, pos_begin);
if (comma_pos != string::npos)
{
tmp = str.substr(pos_begin, comma_pos - pos_begin);
pos_begin = comma_pos + sep.length();
}
else
{
tmp = str.substr(pos_begin);
pos_begin = comma_pos;
}
if (!tmp.empty())
{
result.push_back(tmp);
tmp.clear();
}
}
return 0;
}
去两端空格
std::string DataHelper::trim( const string &str )
{
string::size_type pos = str.find_first_not_of(' ');
if (pos == string::npos)
{
return str;
}
string::size_type pos2 = str.find_last_not_of(' ');
if (pos2 != string::npos)
{
return str.substr(pos, pos2 - pos + 1);
}
return str.substr(pos);
}
测试示例
void DataHelper::test()
{
string fileName = "hello.json";
vector<string> result;
split(fileName, result, ".");
string test = " test ";
trim(test);
}