將字符串以某個分隔符分隔

話不多說,直接上代碼:

// 將str字符串以“division”字符分隔,最終結果生成多個子字符串並保存到vStr中。
void StringSplit(const std::string& str, std::vector<std::string>& vStr, const char& division)
{
	try
	{
		int startPos = 0;
		int endPos = std::string::npos;

		startPos = str.find_first_not_of(division);
		while (startPos != std::string::npos)
		{
			endPos = str.find_first_of(division, startPos);
			if (endPos != std::string::npos)
			{
				std::string strSplit = str.substr(startPos, (endPos - startPos));
				vStr.push_back(strSplit);
			}
			else
			{
				std::string strSplit = str.substr(startPos);
				vStr.push_back(strSplit);
			}
			startPos = str.find_first_not_of(division, endPos);
		}

	}
	catch (const std::exception& e) {
		std::cout << "parse error:" << str << std::endl;
	}
}


int main()
{
    std::string str = "123@456@789";
    std::vector<std::string> vResult;
    StringSplit(str, vResult, '@');
    string data1 = vResult[0];
    string data2 = vResult[1];
    string data2 = vResult[2];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章