explode, split
implode 함수의 반대 동작인 문장의 분리를 하는 explode 역시 vector를 사용해 PHP와 같은 방식으로 구현해보았다.
https://github.com/muabow/home/tree/main/src/cpp/explode
소스코드 내용
#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
'IT > programming' 카테고리의 다른 글
[C/C++] parse mp3 header/C언어 MP3 헤더 분석 함수 공유 (0) | 2022.01.07 |
---|---|
[C/C++] ALSA PCM capture(recoding) 소스 코드 공유 (0) | 2021.12.28 |
[C/C++] implode 구현 방법과 소스코드 공유 (0) | 2021.12.24 |
[C/C++] signal handler library 활용과 소스코드 공유 (0) | 2021.12.24 |
[C/C++] C언어 main 함수 전/후에 함수를 실행 하는 방법 (0) | 2021.12.21 |
댓글