user2796815
user2796815

Reputation: 465

Breaking up a string into separate elements

I'm trying to write an algorithm that will take in a string and find the individual words within it, then push that word into a vector.

void setChar(string s)
{
    {
    int i = 0;


    while(i != s.size())
    {

        while( i != s.size() && isspace(s[i]))
            i++;

        int j = i;

        while(j != s.size() && !isspace(s[j]))
            j++;

        if(i != j)
        {

            words.push_back(s.substr(i, j));
            cout<<"Successfully stored the word "<<s.substr(i, j)<<endl;
            i = j;
        }

    }
    return;
    }
} 

The algorithm runs, but gives me weird results. When I put in the string "The turtle is very happy", I get:

Successfully stored the word the

Successfully stored the word turtle is

Successfully stored the word is very happy

Successfully stored the word very happy

Successfully stored the word happy

I tried debugging it, but everything looks good. I track the i / j variables and they're locating the right indexes for the sub-strings. Any idea as to why I would be getting these results?

Upvotes: 0

Views: 90

Answers (2)

trm
trm

Reputation: 420

The second argument to substr is the number of characters to take, not the index of the last character. To get the result you want, you should use s.substr(i, j-i)

Upvotes: 2

bm2i
bm2i

Reputation: 75

words.push_back(s.substr(i, j-i));
cout<<"Successfully stored the word "<<s.substr(i, j-i)<<endl;

Here's your mistake. You find right location but you get substring wrong. Chang j to j-i when get substring.

Upvotes: 2

Related Questions