Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access individual words after splitting a string?

Tags:

c++

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();
like image 366
thorvald Avatar asked Oct 14 '25 14:10

thorvald


2 Answers

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.

like image 158
Fred Foo Avatar answered Oct 17 '25 03:10

Fred Foo


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.

like image 29
sbi Avatar answered Oct 17 '25 05:10

sbi