6#ifndef YODA_STRINGUTILS_H
7#define YODA_STRINGUTILS_H
20 struct bad_lexical_cast :
public std::runtime_error {
21 bad_lexical_cast(
const std::string& what) : std::runtime_error(what) {}
25 template<
typename T,
typename U>
26 T lexical_cast(
const U& in) {
33 }
catch (
const std::exception& e) {
34 throw bad_lexical_cast(e.what());
41 inline std::string toStr(
const T& x) {
44 return lexical_cast<std::string>(x);
49 inline double toDbl(
const std::string& s) {
54 return std::numeric_limits<double>::quiet_NaN();
60 inline std::string toLower(
const std::string& s) {
62 std::transform(out.begin(), out.end(), out.begin(), (
int(*)(
int)) tolower);
68 inline std::string toUpper(
const std::string& s) {
70 std::transform(out.begin(), out.end(), out.begin(), (
int(*)(
int)) toupper);
76 inline std::string encodeForXML(
const std::string& in) {
78 typedef std::pair<std::string, std::string> CharsToEntities;
79 std::vector<CharsToEntities> cs2es;
80 cs2es.push_back(std::make_pair(
"&",
"&"));
81 cs2es.push_back(std::make_pair(
"<",
"<"));
82 cs2es.push_back(std::make_pair(
">",
">"));
83 for (std::vector<CharsToEntities>::const_iterator c2e = cs2es.begin(); c2e != cs2es.end(); ++c2e) {
84 std::string::size_type pos = -1;
85 while ( ( pos = out.find(c2e->first, pos + 1) ) != std::string::npos ) {
86 out.replace(pos, 1, c2e->second);
94 inline bool contains(
const std::string& s,
const std::string& sub) {
95 return s.find(sub) != std::string::npos;
99 inline bool startswith(
const std::string& s,
const std::string& sub) {
100 return s.find(sub) == 0;
104 inline bool endswith(
const std::string& s,
const std::string& sub) {
105 const size_t pos = s.find(sub);
106 return pos != std::string::npos && pos == (s.size()-sub.size());
111 inline std::string& iltrim(std::string& s) {
112 s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](
unsigned char c){ return !std::isspace(c); }));
118 inline std::string& irtrim(std::string& s) {
119 s.erase(std::find_if(s.rbegin(), s.rend(), [](
unsigned char c){ return !std::isspace(c); }).base(), s.end());
124 inline std::string& itrim(std::string& s) {
125 return iltrim(irtrim(s));
130 inline std::string ltrim(
const std::string& s) {
136 inline std::string rtrim(
const std::string& s) {
142 inline std::string trim(
const std::string& s) {
148 inline std::vector<std::string> split(
const std::string& s,
const std::string& sep) {
149 std::vector<std::string> dirs;
152 const size_t delim_pos = tmp.find(sep);
153 if (delim_pos == std::string::npos)
break;
154 const std::string dir = tmp.substr(0, delim_pos);
155 if (dir.length()) dirs.push_back(dir);
156 tmp.replace(0, delim_pos+1,
"");
158 if (tmp.length()) dirs.push_back(tmp);
165 inline std::vector<std::string> pathsplit(
const std::string& path) {
166 return split(path,
":");
Anonymous namespace to limit visibility.