본문 바로가기
IT/programming

[C/C++] implode 구현 방법과 소스코드 공유

by 어느해겨울 2021. 12. 24.

implode

 

implode는 문장의 결합 역할을 하는 함수이다.

C++ 개발 시 string 관련 처리를 많이 하게 되는데 implode 함수가 없는 거 같아서 vector를 사용해 PHP와 같은 방식으로 구현해보았다. 

 

https://github.com/muabow/home/tree/main/src/cpp/implode

 

GitHub - muabow/home: C/C++, PHP, GO source/library

C/C++, PHP, GO source/library. Contribute to muabow/home development by creating an account on GitHub.

github.com

 

 

소스코드 내용

#include <iostream>
#include <vector>

using namespace std;

string implode(const string _glue, const vector<string> _pieces) {
    int     num_pieces = _pieces.size();
    string  str_result = "";

    for( int idx = 0 ; idx < num_pieces ; idx++ ) {
        str_result += _pieces[idx];
        
        if( idx < num_pieces - 1 ) {
            str_result += _glue;
        }
    }
    
    return str_result;
}


int main(void) {
    vector<string> v_num_list = {"one", "two", "three"};
    
    string str_result = implode("_", v_num_list);
    cout << str_result << endl;

    return 0;
}

C++ STL vector 에 "one" "two" "three"를 넣고 implode를 시켜보았다.

 

 

컴파일

g++ -o implode implode.cpp -std=c++11

 

실행 및 결과

muabow@muabow:~/github/home/library/cpp_implode$ ./implode
one_two_three

 

 

댓글