c++ 分割字串

laremehpe發表於2024-05-27
#include "iostream"
#include "vector"
#include "string"

using namespace std;


vector<string> split(string txt, string splitor)
{
	vector<string> strList;
	const char* arr = txt.c_str();
	size_t last = 0;
	size_t splitorLen = splitor.length();
	size_t len = txt.length();

	for (size_t i = 0; i < len; i++)
	{
		if (splitorLen + i > len) {
			break;
		}
		string cur = txt.substr(i, splitorLen);
		if (cur == splitor) {
			strList.push_back(txt.substr(last, i - last));
			i += splitorLen;
			last = i;
		}
	}

	strList.push_back(string(txt, last, len));

	return strList;
}



void main() {
	string txt = "23456789123456789123456789";
	string splitor = "1";

	vector<string> res = split(txt, splitor);

	for (size_t i = 0; i < res.size(); i++)
	{
	    cout << res.at(i) << "\n" << endl;
	}
}

相關文章