string切割

#incldue 
using namespace std;
#incldue 
#incldue 


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





你可能感兴趣的:(C++)