string切割

#incldue <iostream>
using namespace std;
#incldue <vector>
#incldue <string>


typedef std::vector<std::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<std::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();
	}
}





猜你喜欢

转载自blog.csdn.net/angel69devil/article/details/79243296
今日推荐