Programming/C++

Split 함수 만들기 #2 - string delimiter

moxie2ks 2025. 1. 26. 18:01
728x90
반응형

개요

앞서 포스팅한 글에서 언급했듯이, C++ 에는 delimiter를 이용한 split 함수가 없다. 필요한 경우, split 함수를 직접 만들어 활용해야 한다. 이번 글에서는 delimiter를 char 단위가 아닌 string단위로 활용하여 split 함수를 구현해 보자.

 

💡 delimiter가 char단위가 아닌 string단위이기 때문에, 보다 범용적으로 쓰일 수 있다.

사용 방법

  1. strfind로 delimiter가 해당하는 위치를 찾는다.
  2. 찾을 문자열의 0번째부터 strfind로 찾은 위치까지를 string 형식의 token으로 저장한다.
  3. token을 벡터에 저장한다.
  4. token부분을 찾을 문자열에서 지운다.
  5. 2~4를 반복한다.
  6. 찾을 문자열의 남은 부분을 벡터에 저장한다.
  7. 결과를 리턴한다.

핵심 코드

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
반응형