sf8193
sf8193

Reputation: 635

checking for spaces with c++

So I've looked around the site for someone having a similar issue but nothing has come up and it's really been perplexing me.

#include <iostream>
#include <string>
using namespace std;

string reverse(string s)
{
    int start = 0;
    for(int i = 0; i < s.length(); i++)
    {
        if(s[i]==' '){
            string new_word = s.substr(start,i);
            cout << new_word << endl;
            start = i+1;
         }   
    }
    return "hi";
}



int main(){
    cout << reverse("Hey there my name is am");
    return 0;
}

When I run the tidbit of code above this is what I get as an output.

Hey
there my 
my name is
name is am
is am
hi

as you can see the if condition doesn't seem to break on every space. I have also tried isspace(s[i]) and that produced the same result as above. I cannot for the life of me figure out why the if condition is getting skipped on certain white spaces and not others. Has anyone run into a similar issue?

Upvotes: 0

Views: 1663

Answers (1)

Seeker
Seeker

Reputation: 126

Take a look at the reference of string::substr. It clearly states that len takes the number of characters to include in the substring. In your code you are passing the index of ' ' which is simply wrong because it does not correspond to len. Instead of using s.substr(start,i), simply use s.substr(start,i - start + 1). That should fix the problem.

Upvotes: 1

Related Questions