您的位置:首页 > 编程语言 > C语言/C++

C/C++--字符串切割及去两端空格

2014-03-22 12:39 344 查看
#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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cc++ string trim split string.h