#include #include /* * Explode implementation in C++ * Joe Gillotti - 02/03/2011 */ // split a string. supports more than one character split string. std::vector explode(std::string string, std::string sep) { // Store results we give here std::vector result; // Buffer for found parts of the string std::string curr = ""; // Letter by letter for (int i = 0, len = string.length(); i < len; i++) { // If the seperator string starts here, or if this is the last character if (string.substr(i, sep.length()).compare(sep) == 0 || i == len - 1) { // If it's the last character, make sure we get this part if (i == len - 1 && string.substr(i, sep.length()).compare(sep) != 0) curr += string[i]; // Save result, if it's worth saving if (curr.length() > 0) result.push_back(curr); // Reset buffer for next time curr = ""; // This is for delimitters longer than one char i += sep.length() - 1; } else { // Haven't reached a seperator. Save what we have in the // current buffer curr += string[i]; } } // Give return result; } // Example usage: int main() { // Our sample string std::string words = "test1|test2|test3|test4"; // Run it and get results std::vector result = explode(words, "|"); int num_results = result.size(); // No results? if (num_results == 0) std::cout << "No results" << std::endl; // Yes, there are else { // Give notice std::cout << "Results: " << result.size() << std::endl; // Each, followed by a newline for (int i = 0; i < num_results; i++) std::cout << result[i] << std::endl; } // This was succesful return 0; }