-
-
Save shelllee/cf668cd6cd437ed755a181f3dd11f29c to your computer and use it in GitHub Desktop.
trim for std::string c++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring | |
#include <algorithm> | |
#include <cctype> | |
#include <locale> | |
// trim from start (in place) | |
static inline void ltrim(std::string &s) { | |
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { | |
return !std::isspace(ch); | |
})); | |
} | |
// trim from end (in place) | |
static inline void rtrim(std::string &s) { | |
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { | |
return !std::isspace(ch); | |
}).base(), s.end()); | |
} | |
// trim from both ends (in place) | |
static inline void trim(std::string &s) { | |
ltrim(s); | |
rtrim(s); | |
} | |
// trim from start (copying) | |
static inline std::string ltrim_copy(std::string s) { | |
ltrim(s); | |
return s; | |
} | |
// trim from end (copying) | |
static inline std::string rtrim_copy(std::string s) { | |
rtrim(s); | |
return s; | |
} | |
// trim from both ends (copying) | |
static inline std::string trim_copy(std::string s) { | |
trim(s); | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment