Marco Dorantes' WebLog

"Computer science is no more about computers than astronomy is about telescopes" -Edsger W. Dijkstra

String trim with ISO C++

String trim with ISO C++

  • Comments 1

Do you want a trim function for strings using ISO C++ and no more? like this:

#include <iostream>
#include <string>

void main()
{
 assert_equal("ab b",trim(std::string(" ab b ")));
 assert_equal("ab b",trim(std::string("  ab b")));
 assert_equal("ab b",trim(std::string("ab b  ")));
}

void assert_equal(const std::string& s1,const std::string& s2)
{
 if( s1 == s2 ) return;
 std::cout << "not equal:\ns1:[" << s1 << "]\ns2:[" << s2 << "]\n";
}

Here is one:
std::string trim(std::string& s,const std::string& drop = " ")
{
 std::string r=s.erase(s.find_last_not_of(drop)+1);
 return r.erase(0,r.find_first_not_of(drop));
}
Leave a Comment
  • Please add 4 and 7 and type the answer here:
  • Post