Tell me, how can I use <vector> to split the string I need into substrings that will be stored in an array, no?
Need from:
"Hello how are you"
Receive:
str[0]="Привет"; str[1]="Как"; str[2]="Дела"; As in PHP - explode, and C # - split
Tell me, how can I use <vector> to split the string I need into substrings that will be stored in an array, no?
Need from:
"Hello how are you"
Receive:
str[0]="Привет"; str[1]="Как"; str[2]="Дела"; As in PHP - explode, and C # - split
It seems that this is what you wanted:
#include <iostream> #include <vector> #include <string> using namespace std; int main () { vector<string> arr; string str ("Привет; Как; Дела"); string delim("; "); size_t prev = 0; size_t next; size_t delta = delim.length(); while( ( next = str.find( delim, prev ) ) != string::npos ){ //Отладка-start string tmp = str.substr( prev, next-prev ); cout << tmp << endl; //Отладка-end arr.push_back( str.substr( prev, next-prev ) ); prev = next + delta; } //Отладка-start string tmp = str.substr( prev ); cout << tmp << endl; //Отладка-end arr.push_back( str.substr( prev ) ); return 0; } There is no standard way. You need to 1) either write your function, 2) either connect an external library, 3) either convert std::string to c_str and use strtok . For example,
char *s = new char[source.size() + 1]; strcpy(s, source.c_str()); char *p = strtok(s, ";"); while (p! = NULL) { cout << p << endl; p = strtok(NULL, ";"); } delete[] s; More " C++ " method is as follows:
std::string sentence = "Hello how are you"; std::istringstream iss(sentence); std::vector<std::string> tokens; std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(tokens)); In this case, however, you can not specify your own separator. As a more convenient alternative, I can offer boost::string_algo .
This implementation even works on msvc2010
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; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } int main(int argc, char** argv) { std::string sText; std::getline(std::cin, sText); std::vector<std::string> sWords = split(sText, ';'); return 0; } Source: https://ru.stackoverflow.com/questions/49525/
All Articles