Store Words from space separated string

Can anyone help me … How can I store a vector of string from a long string separated by space-like " I am a good boy"
so vector contains (“I” , “am” , “a” , “good”,“boy”) like that…
I Know the basic algo like iterate each character until space comes and when space comes the word is push back to vector, but i need shorter in CPP
@ssjgz @l_returns bro help na :slight_smile:

1 Like

Unfortunately, the C++ Standard Library still doesn’t have a split function, though third-party libraries like Boost provide one, and there will eventually be something similar in the C++20 library.

So for the time being, you’re stuck with this.

#include <bits/stdc++.h> 
#define ll long long
using namespace std; 

void SplitString(string str, string delimiter, std::vector<string> &container){
  ll pos = 0;
  std::string token;
  while ((pos = str.find(delimiter)) != std::string::npos) {
      token = str.substr(0, pos);
      str.erase(0, pos + delimiter.length());

int main() 
{   ios_base::sync_with_stdio(false);

    string mystring = "I am a good boy"; //Your String
    string delimiter = " "; //Explode on Space

    std::vector<string> TheSplitStringVector; //Creating a vector for holding  words

    SplitString(mystring, delimiter,TheSplitStringVector); //I used void for the function and passed an empty vector by reference to avoid overhead.

    for (auto& it : TheSplitStringVector) {
    cout << it << endl;

    return 0; 

Hope this help. :slight_smile:

@ssrivastava990 @ssjgz @hackinet There is a easy way out using string stream. Using stringstream in c++. Just 4 lines of code.

string input="I am a bad red coder";
stringstream ss(input);
string temp;
while (ss>>temp)//one by one space separated tokens are copied to temp

Hola! That’s it!
stringstream is a buffer just like cin. Just like cin starts new input from space, it does the similar thing.

1 Like

@ssrivastava990 I think this soln works for you

1 Like