std::remove()



  • Hallo,

    Ich versuche mit std::remove() alle Leerzeichen eines Stringes vor dem ersten "Nichtleerzeichen" und nach dem letzten "Nichtleerzeichen" abzuscheiden.

    Dies will jedoch nicht funktionieren, hier mein Sourcecode:

    // Find the first position that is not a space
            string line = "         hallo";
            unsigned short endPosition = 0;
            for (unsigned short i = 0; i < line.length(); i++) {
                if (line[i] != ' ') {
                    endPosition = i;
                    break;
                }
            }
            if (endPosition > 0) {
          //      cout << *(line.begin() + endPosition) << endl; // gibt "h" aus
                std::remove(line.begin(), (line.begin() + endPosition), ' ');
            }
    

    Leider ändert sich nichts am string, seht ihr vielleicht das Problem/den Fehler?

    Danke schon im voraus!



  • Tipp1: std::remove kopiert höchstens nur ein paar Elemente um. In Deinem Fall macht es so gut wie gar nichts (absichtlich)

    Tipp2: Suchst Du vielleicht die erase-Methode von string?



  • Oder falls du es nur mit STL-Algorithmen machen willst:

    bool not_space(char c)
    {
        return c != ' ';
    }
    
    int main()
    {
        std::string line = "         hallo";
        std::string::iterator pos = std::find_if(line.begin(), line.end(), &not_space);
        line.erase(line.begin(), pos);
    }
    


  • krümelkacker schrieb:

    Tipp1: std::remove kopiert höchstens nur ein paar Elemente um. In Deinem Fall macht es so gut wie gar nichts (absichtlich)

    Tipp2: Suchst Du vielleicht die erase-Methode von string?

    Dankeschön!



  • Trim:

    size_t trim;
    	if( (trim = context.find_first_not_of( _T(" \t") )) != wstring::npos )
    		context.erase( 0, trim );
    	if( (trim = context.find_last_not_of( _T(" \t") )) != wstring::npos )
    		context.resize( trim+1 );
    

Anmelden zum Antworten