implementing split function in c++
// splits a std::string into vector<string> at a delimiter vector<string> split(string x, char delim = ' ') { x += delim; //includes a delimiter at the end so last word is also read vector<string> splitted; string temp = ""; for (int i = 0; i < x.length(); i++) { if (x[i] == delim) { splitted.push_back(temp); //store words in "splitted" vector temp = ""; i++; } temp += x[i]; } return splitted; }
c++ string split
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while(std::getline(ss, item, delim)) { elems.push_back(item); } return elems; }
Source: stackoverflow.com
how to split a string in c++
#include <iostream> #include <sstream> #include <vector> using namespace std; // for string delimiter vector<string> split (string s, string delimiter) { size_t pos_start = 0, pos_end, delim_len = delimiter.length(); string token; vector<string> res; while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { token = s.substr (pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; res.push_back (token); } res.push_back (s.substr (pos_start)); return res; } int main() { string str = "adsf-+qwret-+nvfkbdsj-+orthdfjgh-+dfjrleih"; string delimiter = "-+"; vector<string> v = split (str, delimiter); for (auto i : v) cout << i << endl; return 0; }
Source: stackoverflow.com
c ++ split_string
std::vector<std::string> split_string(const std::string& str, const std::string& delimiter) { std::vector<std::string> strings; std::string::size_type pos = 0; std::string::size_type prev = 0; while ((pos = str.find(delimiter, prev)) != std::string::npos) { strings.push_back(str.substr(prev, pos - prev)); prev = pos + 1; } // To get the last substring (or only, if delimiter is not found) strings.push_back(str.substr(prev)); return strings; }
Source: stackoverflow.com
split text c++
#include <boost/algorithm/string.hpp> std::string text = "Let me split this into words"; std::vector<std::string> results; boost::split(results, text, [](char c){return c == ' ';});
Source: www.fluentcpp.com