프로그래밍/C++

c++ 문자열을 배열로 변환(explode) 방법

소행성왕자 2021. 12. 8. 15:03

php 의 explode 와 같이 문자열을 특정 구분자로 배열로 변환해 보겠습니다.

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <sstream>
#include <utility>
std::string exec(const char* cmd) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (fgets(buffer, sizeof buffer, pipe) != NULL) {
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return result;
}
template <typename Out>
void split(const std::string &s, char delim, Out result) {
std::istringstream iss(s);
std::string item;
while (std::getline(iss, item, delim)) {
*result++ = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
int main()
{
std::vector<std::string> x = split("one:two::three", ':');
for(int i=0; i<x.size(); i++) {
std::cout << x[i] << std::endl;
}
}

result

$ ./cpp
one
two
three