W3Ask






HOME  >  PROGRAMMING  >  GLOBAL PROGRAMMING

Split a string in C++




How to split a string in C++. We often need to cut strings when we are working on a text editor, when we want to propose internet users to quote certain parts of a text. When we offer the possibility to quickly edit a message.

Here are several solutions to do so:

Solution 1 :

#include 
#include
#include

int main(){
std::string s("Somewhere down the road");
std::istringstream iss(s);

do{
std::string sub;
iss >> sub;
std::cout << "Substring: " << sub << std::endl;
} while (iss);
}

Solution 2 :

#include 
#include
#include
#include
#include

int main() {
using namespace std;
string sentence = "And I feel fine...";
istringstream iss(sentence);
copy(istream_iterator(iss),
istream_iterator(),
ostream_iterator(cout, "
"));
}

Solution 3 :

#include 
#include
#include

void split(const std::string &s, char delim, std::vector &elems) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
}

std::vector split(const std::string &s, char delim) {
std::vector elems;
split(s, delim, elems);
return elems;
}








Related posts:


No related posts.