본문 바로가기
개발/Tip

C++ 문자열 Split 함수

by jeounpar 2023. 3. 24.
#include <bits/stdc++.h>

using namespace std;

vector<string> split(string input, string delimiter)
{
	vector<string> ret;
	long long pos = 0;
	string token = "";
	while ((pos = input.find(delimiter)) != string::npos)
	{
		token = input.substr(0, pos);
		ret.push_back(token);
		input.erase(0, pos + delimiter.length());
	}
	ret.push_back(input);
	return ret;
}

 

예시

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

vector<string> split(string input, string delimiter) {
  vector<string> ret;
  long long pos = 0;
  string token = "";
  while ((pos = input.find(delimiter)) != string::npos) {
    token = input.substr(0, pos);
    ret.push_back(token);
    input.erase(0, pos + delimiter.length());
  }
  ret.push_back(input);
  return ret;
}

int main(void) {
  vector<string> tmp = split("Hello World! Bye World!", " ");
  for (auto token : tmp)
    cout << "token = " << token << "\n";
  return 0;
}