c++ split string by several space
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::string sentence = "This is a sample sentence with multiple spaces";
std::istringstream iss(sentence);
std::vector<std::string> tokens;
std::string token;
while (std::getline(iss, token, ' ')) {
if (!token.empty()) {
tokens.push_back(token);
}
}
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
This C++ code segment splits a string named sentence
by multiple spaces. It utilizes std::istringstream
from <sstream>
to separate the string into tokens and stores them in a std::vector<std::string>
. The while
loop reads the string using std::getline
with space (' ') as the delimiter, and if the extracted token is not empty, it's added to the tokens
vector. Finally, the code prints each token from the vector tokens
to the standard output.