7K4B blog

猫でも分かる何か

文字列の複数分割 auto string_split

auto string_split

文字列の複数分割
文字長N のとき計算量  O(N \log N)

1-indexなので注意(例 0文字目と1文字目の境界で分割するときはpos=1を渡す)pos=0だけを指定したときは分割なし

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using setl = set<ll>;
using vs = vector<string>;

auto string_split = [&](string& s, setl& pos) -> vs {
	vs res; string test;
	test += s[0];
	for (ll i = 1; i < (ll)s.size(); i++) {
		if (pos.find(i) != pos.end()) res.push_back(test), test.clear();
		test += s[i];
	}
	res.push_back(test);
	return res;
};
how to use
int main() {
	setl pos;
	string s = "abcd";
	auto res1 = string_split(s, pos);
	cout << "pos="; for (auto& e : pos) cout << e << ","; cout << endl;
	cout << "res1="; for (auto& e : res1) cout << e << ","; cout << endl;
	pos.insert(0);
	auto res2 = string_split(s, pos);
	cout << "pos="; for (auto& e : pos) cout << e << ","; cout << endl;
	cout << "res2="; for (auto& e : res2) cout << e << ","; cout << endl;
	pos.insert(1);
	auto res3 = string_split(s, pos);
	cout << "pos="; for (auto& e : pos) cout << e << ","; cout << endl;
	cout << "res3="; for (auto& e : res3) cout << e << ","; cout << endl;
	return 0;
}
pos=
res1=abcd,
pos=0,
res2=abcd,
pos=0,1,
res3=a,bcd,