samedi 19 septembre 2020

Splitting a string into a vector

I was trying to write a program to split a string into substrings and storing each word in a vector. However unfortunately my function was only splitting the string when the following word is one letter bigger than the previous word i.e: I am very happy but when it comes to splitting a string with mixed length words it doesn't work properly.

Could someone tell me where I have gone wrong? I would appreciate it

void delimit(string &str)
{
    vector<string> delimitedStr;
    string word;
    int i = 0;
    while (i < str.size())
    {
        if (isSpace(str.at(i)))
        {
            word = str.substr(0, i);
            delimitedStr.push_back(word);
            str.erase(0, i + 1);
            // delimitedStr.push_back(word);
        }
        i++;
    }
    for (int i = 0; i < delimitedStr.size(); i++)
    {
        cout << delimitedStr.at(i) << endl;
    }
}

Aucun commentaire:

Enregistrer un commentaire