how to divide a sentence contained in a string into words and push back to a vector.



Hello ,



I have sentence like " I am King" in a string or character array.
I want this string to be placed in a vector<string> object.

vector<string> a;
Like a[0] -> I
a[1]-> am
a[2] -> king

How do I do that ,,

I have tried this method but it doesn't work :




char ch1[20];
vector<string> a;
string temp;

cout<<"Enter something:";
gets(ch1);


int length1 = strlen(ch1);
for(int i = 0;i<length1;i++)
{

for(int j = i;j < length1;j++)
{
if(ch1[j] == ' ')
{
for(int c = i;c <= j;c++)
{
temp.push_back(ch1[c]);
}
a.push_back(temp);
temp.clear();
break;
}

}

}

for(int i=0;i<a.size();i++)
{
cout<<a[i]<<" ";
}

Firstly, use code tags.
Secondly, you need to get the input into a string, preferably not a char[]
Thirdly, all you need to do is find ' ' characters and their location, and use them as slice indices. So:
"I am king"
Spaces at: 2 and 5
So then all chars between: 1; 3+4; 6-END
are your words you need to push.

But how can we trace element at each and every position if we use strings?
If you are using a character array then you can use C function std::strtok to split the array into tokens (words).
The other way is to use std::istringstream and std::string

For example

1
2
3
4
5
6
7
8
9
10
11
std::vector<std::string> v;
std::string s;

std::cout << "Enter something: ";   // :)
std::getline( std::cin, s );

std::istringstream is( s );

std::string word;

while ( is >> word ) v.push_back( word );

I do not completely understand your question (so i am going on what i assume it means).
Strings can also be indexed like char[].
1
2
string s="hello";
cout<<s[1];

Output:
e
closed account (DSLq5Di1)
http://ideone.com/0IRhe
I have solved this program finally , Thank you very much for your support.

#include <stdio.h>
#include <iostream>
#include <string>

#include <vector>
using namespace std;

int main()
{

string str;

vector<string> a;
vector<string>::iterator it;

char word[40];

cout<<"Please enter something :"<<endl;

gets(word);

int pos;

int length = strlen(word);


// copy the sentence into a vector
for(int i=0;i<length;i++)
{
str.push_back(word[i]);

if(word[i] == ' ' || i == length - 1 )
{
a.push_back(str);
str.clear();
continue;
}

}

for(it = a.begin();it <a.end();it++)
{
cout<<*it<<" ";
}

cout<<endl;

system("pause");

}


Topic archived. No new replies allowed.