mardi 26 mai 2015

std::string find() inside string erase() , erases everything ahead of 1st find/occurence

I'm still having difficulty to phrase title for this question , take a look at this code :

#include <iostream>
#include <string>
#include <algorithm>

int main(){
    std::string s1 = " Hello World  1 ";
    std::string s2 = " Hello World  2 ";
    while(s1.find(' ') != std::string::npos){
        s1.erase(s1.find(' '));
    }
    while(s2.find(' ') != std::string::npos){
        s2.erase(std::find(s2.begin() , s2.end() ,' '));
    }
    std::cout<<s1<<"\n";
    std::cout<<s2;
    return 0;
}

I'm using std::string::find() to detect the presence of whitespace inside string , and if still present , use std::string::erase() to delete them.

I've tried two different methods of doing this:

s1.erase(s1.find(' '));

and

s2.erase(std::find(s2.begin() , s2.end() ,' '));

however in 1st method , it finds the 1st occurence of ' ' whitespace inside string and deletes everything ahead of it. 2nd method works as expected.

Current Ouptut is :

HelloWorld2

Can anyone tell me what is the reason behind 1st method deleting everything ahead of 1st occurence? For quick glance : link

Relevant links :

std::basic_string::find

std::find

std::basic_string::erase

Aucun commentaire:

Enregistrer un commentaire