아쉽게도 C++에서는 std::string에 대해서 특정 문자나 문자열에 대해 split해서 반환해주는 편리한 함수가 존재하지 않는다.
자주 쓸 일이 있는 함수임에도 기본제공하지 않는다는 점이 아쉬워 개인적으로 사용하기 위해서 간단하게 함수를 만들어 보았다.
※ 개인적으로 사용하기 위해 만들어 본 함수이므로 예상치 못한 버그가 존재할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #include <string> #include <iostream> #include <vector> std::vector<std::string> Split(std::string targetStr, std::string token) { // Check parameters if(token.length() == 0 || targetStr.find(token) == std::string::npos) return std::vector<std::string>({targetStr}); // return var std::vector<std::string> ret; int findOffset = 0; int splitOffset = 0; while ((splitOffset = targetStr.find(token, findOffset)) != std::string::npos) { ret.push_back(targetStr.substr(findOffset, splitOffset - findOffset)); findOffset = splitOffset + token.length(); } ret.push_back(targetStr.substr(findOffset, targetStr.length() - findOffset)); return ret; } int main() { // Test std::vector<std::string> splitted = Split("Hello World a b c", " "); for(auto s : splitted) std::clog << s << std::endl; std::clog << "=================================" << std::endl; std::vector<std::string> splitted2 = Split("abcd//ef//gh//ijk", "//"); for (auto s : splitted2) std::clog << s << std::endl; return 0; } | cs |
'Programming' 카테고리의 다른 글
[Python] 데코레이터(Decorator)의 이해 (0) | 2018.03.11 |
---|---|
[Python] 파이썬 2 에서의 Division(나누기) 문제 (0) | 2018.02.07 |
CodeFights - alternatingSums (0) | 2018.01.15 |
CodeFights - commonCharacterCount (0) | 2017.12.27 |
[Hooking] notepad.exe 후킹 다시 공부 (0) | 2017.07.24 |