字符串分割

用STL進行字符串的分割 

涉及到string類的兩個函數find和substr:
1、find函數
原型:size_t find ( const string& str, size_t pos = 0 ) const;
功能:查找子字符串第一次出現的位置。
參數說明:str爲子字符串,pos爲初始查找位置。
返回值:找到的話返回第一次出現的位置,否則返回string::npos 

2、substr函數
原型:string substr ( size_t pos = 0, size_t n = npos ) const;
功能:獲得子字符串。
參數說明:pos爲起始位置(默認爲0),n爲結束位置(默認爲npos)
返回值:子字符串 

//字符串分割函數
	std::vector<std::string> split(std::string str, std::string pattern)
	{
		std::string::size_type pos;
		std::vector<std::string> result;
		str += pattern;//擴展字符串以方便操作
		int size = str.size();

		for (int i = 0; i < size; i++)
		{
			pos = str.find(pattern, i);
			if (pos < size)
			{
				std::string s = str.substr(i, pos - i);
				result.push_back(s);
				i = pos + pattern.size() - 1;
			}
		}
		return result;
	}

博客參考:字符串分割 (C++)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章