[c++] 문자열 분할 (스플릿)
C++에서 문자열을 특정 구분자를 기준으로 분할하는 방법에 대해 알아보겠습니다.
1. strtok 함수를 사용한 방법
#include <iostream>
#include <cstring>
int main() {
char str[] = "apple,orange,banana";
char* token = std::strtok(str, ",");
while (token != NULL) {
std::cout << token << std::endl;
token = std::strtok(NULL, ",");
}
return 0;
}
2. string과 find 함수를 사용한 방법
#include <iostream>
#include <string>
int main() {
std::string str = "apple,orange,banana";
size_t pos = 0;
std::string token;
while ((pos = str.find(",")) != std::string::npos) {
token = str.substr(0, pos);
std::cout << token << std::endl;
str.erase(0, pos + 1);
}
std::cout << str << std::endl;
return 0;
}
3. Boost 라이브러리 사용하기
Boost 라이브러리를 사용하면 간편하게 문자열을 분할할 수 있습니다.
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <vector>
#include <string>
int main() {
std::string str = "apple,orange,banana";
std::vector<std::string> tokens;
boost::split(tokens, str, boost::is_any_of(","));
for (auto token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
결론
C++에서는 strtok 함수, string과 find 함수, 그리고 Boost 라이브러리를 사용하여 문자열을 특정 구분자를 기준으로 간편하게 분할할 수 있습니다.
참고 문헌:
- http://www.cplusplus.com/reference/cstring/strtok/
- http://www.cplusplus.com/reference/string/string/find/
- https://www.boost.org/doc/libs/1_77_0/doc/html/boost/algorithm/split.html