본문 바로가기
IT/programming

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

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

explode, split

 

implode 함수의 반대 동작인 문장의 분리를 하는 explode 역시 vector를 사용해 PHP와 같은 방식으로 구현해보았다.

 

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

 

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;

vector<string> explode(const string _delimiter, const string _string) {
	size_t pos_start = 0, pos_end, delim_len = _delimiter.length();
	string token;
	vector<string> v_list;

	while( (pos_end = _string.find(_delimiter, pos_start)) != std::string::npos ) {
		token = _string.substr (pos_start, pos_end - pos_start);
		pos_start = pos_end + delim_len;
		v_list.push_back(token);
	}

	v_list.push_back(_string.substr(pos_start));
	
	return v_list;
}

int main(void) {
    string str_num_list = "one_two_three";
    
    vector<string> v_num_list = explode("_", str_num_list);
    for( int idx = 0 ; idx < (int)v_num_list.size() ; idx++ ) {
        cout << v_num_list[idx] << endl;
    }

    return 0;
}

C++ string에 "one_two_three" 를 넣고 "_"를 delimiter로 사용하여 explode를 시켜보았다.

 

 

컴파일

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

 

실행 및 결과

muabow@muabow:~/github/home/library/cpp_explode$ ./explode
one
two
three

 

 

댓글