thorvald
thorvald

Reputation: 227

How do I access individual words after splitting a string?

std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token[0] << "\n";

This is printing individual letters. How do I get the complete words?

Updated to add:

I need to access them as words for doing something like this...

if (word[0] == "something")
   do_this();
else
   do_that();

Upvotes: 4

Views: 1100

Answers (5)

sbi
sbi

Reputation: 224049

You would first have to define what makes a word.

If it's whitespace, iss >> token is the default option:

std::string line("This is a sentence.");
std::istringstream iss(line);

std::vector<std::string> words. 
std::string token;
while(iss >> token)
  words.push_back(token);

This should find

This
is
a
sentence.

as words.

If it's anything more complicated than whitespace, you will have to write your own lexer.

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363547

std::string token, line("This is a sentence.");
std::istringstream iss(line);
getline(iss, token, ' ');

std::cout << token << "\n";

To store all the tokens:

std::vector<std::string> tokens;
while (getline(iss, token, ' '))
    tokens.push_back(token);

or just:

std::vector<std::string> tokens;
while (iss >> token)
    tokens.push_back(token);

Now tokens[i] is the ith token.

Upvotes: 5

TreDubZedd
TreDubZedd

Reputation: 2556

You've defined token to be a std::string, which uses the index operator [] to return an individual character. In order to output the entire string, avoid using the index operator.

Upvotes: 0

tpv
tpv

Reputation: 153

Just print token, and do the getline again.

Upvotes: 0

Ronnie Howell
Ronnie Howell

Reputation: 639

Your token variable is a String, not an array of strings. By using the [0], you're asking for the first character of token, not the String itself.

Upvotes: 1

Related Questions