stringカット
2765 ワード
#incldue
using namespace std;
#incldue
#incldue
typedef std::vector<:string> vecStr;
void SubStr(vecStr& toke, const std::string& src, const std::string& spec)
{
size_t Pos = 0;
size_t Pre = 0;
while (Pos != std::string::npos)
{
/*if (Pre == 0)
{
Pos = src.find(spec, Pre);
}
else
{
Pos = src.find(spec, Pre + 1);
}*/
Pos = src.find(spec, Pre);//find [pos, end)
if (Pos == std::string::npos)
{
/*if (Pre != std::string::npos)
{
string tmp = src.substr(Pre, src.size() - Pre);
cout << tmp << endl;
}*/
string tmp = src.substr(Pre, Pos);
//cout << tmp << endl;
if (!tmp.empty())
{
toke.push_back(tmp);
}
break;
}
/*if (Pre == 0)
{
string tmp = src.substr(Pre, Pos - Pre);
cout << tmp << endl;
}
else
{
string tmp = src.substr(Pre, Pos-Pre);
cout << tmp << endl;
}*/
string tmp = src.substr(Pre, Pos - Pre); //substr pos len
//cout << tmp << endl;
toke.push_back(tmp);
Pre = Pos + spec.size();
}
}
int main(int argc, char* argv[])
{
string a("123|456|789");
//string a("123|456|789|");
//string a("123abc456abc789abc");
vecStr vecstr;
SubStr(vecstr, a, "|");
for (vecStr::iterator it = vecstr.begin(); it != vecstr.end(); ++it)
{
cout << *it << endl;
}
}
上にはいくつかの書き込みプロセスが設計されています.下には最終コードがあります.
typedef std::vector<:string> vecStr;
void SubStr2(vecStr& toke, const std::string& src, const std::string& spec)
{
size_t Pos = 0;
size_t Pre = 0;
while (Pos != std::string::npos)
{
Pos = src.find(spec, Pre);
if (Pos == std::string::npos)
{
string tmp = src.substr(Pre, Pos);
if (!tmp.empty())
{
toke.push_back(tmp);
}
break;
}
string tmp = src.substr(Pre, Pos - Pre);
toke.push_back(tmp);
Pre = Pos + spec.size();
}
}