trim.h

00001 // Found at:
00002 // http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring
00003 
00004 // Note that these functions trim the same arguments passed in, and do not
00005 // make copies.
00006 
00007 #ifndef __BARRY_TRIM_H__
00008 #define __BARRY_TRIM_H__
00009 
00010 #include <algorithm>
00011 #include <functional>
00012 #include <locale>
00013 
00014 namespace Barry { namespace Inplace {
00015 
00016 // trim from start
00017 static inline std::string &ltrim(std::string &s) {
00018         s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
00019         return s;
00020 }
00021 
00022 // trim from end
00023 static inline std::string &rtrim(std::string &s) {
00024         s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
00025         return s;
00026 }
00027 
00028 // trim from both ends
00029 static inline std::string &trim(std::string &s) {
00030         return ltrim(rtrim(s));
00031 }
00032 
00033 }} // namespace Barry::Inplace
00034 
00035 #endif
00036