I have a string variable
string = " this is my string"
I want to store every word separated by a whitespace into an array
- array[0]="this";
- array[1]="is";
- array[2]="my";
- array[3]="string";
I have a string variable
string = " this is my string"
I want to store every word separated by a whitespace into an array
 
    
     
    
    First you have to include "sstream" class like:
#include <sstream>
Then use below code:
    string str= "this is my string"
    int len = str.length();
    string arr[len];
    int i = 0;
    stringstream ssin(str);
    while (ssin.good() && i < len){
        ssin >> arr[i];
        ++i;
    }
    for(i = 0; i < len; i++){
        cout << arr[i] << endl;
    }
 
    
    You could use std::copy with std::istringstream and std::istream_iterator and std::back_inserter:
vector<string> v;
istringstream ss(" this is my string");
copy(istream_iterator<string>(ss), istream_iterator<string>(), back_inserter(v));
 
    
    For this case, you can use string delimiter concept
 strtok(const char * str, int delimiter);
for your case, delimiter is "white space".
program:
 #include <stdio.h>
 #include <string.h>
 int main ()
 {
     char str[] ="This a sample string";
     char * output_after_delimiter_applied;
     char *out_arr[4];
     int i=0;
     printf("The original string is %s\n", str);
     output_after_delimiter_applied = strtok (str," ");
     while (output_after_delimiter_applied != NULL)
     {
         out_arr[i] = output_after_delimiter_applied;
         output_after_delimiter_applied = strtok (NULL, " ");    
                   // NULL parameter is for continuing the search
                  //  delimiter is "white space".
         i++;
     }
     for(i=0; i < 4 ; i++)
         printf("%s\n", out_arr[i]); 
     return 0;
  }
we can add any no. of delimiters with in double quotes. it is like string (delimiter) search.
