728x90
반응형
개요
앞서 포스팅한 글에서 언급했듯이, C++ 에는 delimiter를 이용한 split 함수가 없다. 필요한 경우, split 함수를 직접 만들어 활용해야 한다. 이번 글에서는 delimiter를 char 단위가 아닌 string단위로 활용하여 split 함수를 구현해 보자.
💡 delimiter가 char단위가 아닌 string단위이기 때문에, 보다 범용적으로 쓰일 수 있다.
사용 방법
- strfind로 delimiter가 해당하는 위치를 찾는다.
- 찾을 문자열의 0번째부터 strfind로 찾은 위치까지를 string 형식의 token으로 저장한다.
- token을 벡터에 저장한다.
- token부분을 찾을 문자열에서 지운다.
- 2~4를 반복한다.
- 찾을 문자열의 남은 부분을 벡터에 저장한다.
- 결과를 리턴한다.
핵심 코드
vector<string> split(string input, string delimiter) {
vector<string> result;
size_t pos = 0;
string token; // define a string variable
// use find() function to get the position of the delimiters
while ((pos = input.find (delimiter)) != string::npos)
{
token = input.substr(0, pos);
result.push_back(token); // store the substring
/* erase() function store the current positon and move to next token. */
input.erase(0, pos + delimiter.length());
}
result.push_back(input); // store the remain
return result;
}
예제 코드
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(string input, string delimiter) {
vector<string> result;
size_t pos = 0;
string token; // define a string variable
// use find() function to get the position of the delimiters
while ((pos = input.find (delimiter)) != string::npos)
{
token = input.substr(0, pos);
result.push_back(token); // store the substring
/* erase() function store the current positon and move to next token. */
input.erase(0, pos + delimiter.length());
}
result.push_back(input); // store the remain
return result;
}
int main()
{
string str = "Hello_*_beautiful_*_world_*_in_*_the_*_universe_*_!_*_!_*_";
string delimiter = "_*_";
vector<string> ret = split(str, delimiter);
for(auto i:ret)
cout<<i<<endl;
}
결과
참고
728x90
반응형
'Programming > C++' 카테고리의 다른 글
Vector 최대값, 최소값, 인덱스 구하기 (2) | 2025.02.04 |
---|---|
람다 식(Lambda Expression) (2) | 2025.01.30 |
string - substr 함수 (0) | 2025.01.29 |
vector정렬시 변경된 index도 정렬하기 (0) | 2025.01.28 |
Split 함수 만들기 #1 - char delimiter (0) | 2025.01.25 |