Avatar ·

String splitting in C++ by delimiter — how to do split?

Hello everyone! I've just started learning C++ and encountered a task that in other languages is solved with a single function. I need to split a string into parts by a delimiter (for example, by a comma character or by the substring "::"). In Python I write `"a,b,c".split(",")` and get a list. In C++ I can't find anything like that in the standard library. There is `strtok` from C, but it works with `char*`, and I need to work with `std::string`. Additionally, `strtok` modifies the original string and is not thread-safe. I tried writing my own implementation, but it works poorly: ```cpp #include #include std::vector split(std::string s, std::string delimiter) { size_t pos = 0; std::vector tokens; while ((pos = s.find(delimiter)) != std::string::npos) { std::string token = s.substr(0, pos); tokens.push_back(token); s.erase(0, pos + delimiter.length()); } tokens.push_back(s); return tokens; } ```