开发者

How do I access individual words after splitting a string?

开发者 https://www.devze.com 2023-01-27 10:38 出处:网络
std::string token, line(\"This is a sentence.\"); std::istringstream iss(line); getline(iss, token, \' \');
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 ith 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号