[알고리즘 기초]. C++ split()함수 구현

베뉴·2022년 11월 25일
0

C++은 다 좋은데 안타깝게도 STL에 문자열을 구분자로 자르는 split()함수가 없다.
그래서 우리가 직접 문자열을 자를 때는 함수를 구현해야 하는 약간의(?) 번거로움이 있다.
그러나 밑의 코드 6줄만 외우면 금방 구현할 수 있으므로 외워두자.

💻 [코드 템플릿]

string token = "";
while((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;




이제 문제를 풀어보자.

  • abcdabc를 입력값으로 받아서, d를 구분자로 하여 {abc, abc}를 출력하는 코드를 구현하시오.



    💻 [코드]
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> split(string input, string delimiter) {
  vector<string> ret;
  int pos;
  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() {
  ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
  string s = "abcdabc", d = "d";
  vector<string> ans = split(s, d);
  for(string b: ans) cout << b << "\n";
}
profile
백문이불여일타(이전 블로그: https://blog.naver.com/christer10)

0개의 댓글