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 i开发者_JAVA百科ndividual 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();
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 i
th token.
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.
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.
Just print token, and do the getline again.
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.
精彩评论