c++stringstdvector

How to get a word vector from a string?


I want to store words separated by spaces into single string elements in a vector. The input is a string that may end or may not end in a symbol( comma, period, etc.) All symbols will be separated by spaces too.

I created this function but it doesn't return me a vector of words.

vector<string> single_words(string sentence)
{
    vector<string> word_vector;
    string result_word;

    for (size_t character = 0; character < sentence.size(); ++character)
    {
        if (sentence[character] == ' ' && result_word.size() != 0)
        {
            word_vector.push_back(result_word);
            result_word = "";
        }
        else
            result_word += character;
    }
    return word_vector;
}

What did I do wrong?


Solution

  • You added the index instead of the character:

    vector<string> single_words(string sentence)
    {
        vector<string> word_vector;
        string result_word;
    
        for (size_t i = 0; i < sentence.size(); ++i)
        {
            char character = sentence[i];
            if (character == ' ' && result_word.size() != 0)
            {
                word_vector.push_back(result_word);
                result_word = "";
            }
            else
                result_word += character;
        }
        return word_vector;
    }