6#ifndef YODA_STRINGUTILS_H
7#define YODA_STRINGUTILS_H
19 struct bad_lexical_cast :
public std::runtime_error {
20 bad_lexical_cast(
const std::string& what) : std::runtime_error(what) {}
24 template<
typename T,
typename U>
25 T lexical_cast(
const U& in) {
32 }
catch (
const std::exception& e) {
33 throw bad_lexical_cast(e.what());
40 inline std::string toStr(
const T& x) {
43 return lexical_cast<std::string>(x);
48 inline std::string toLower(
const std::string& s) {
50 std::transform(out.begin(), out.end(), out.begin(), (
int(*)(
int)) tolower);
56 inline std::string toUpper(
const std::string& s) {
58 std::transform(out.begin(), out.end(), out.begin(), (
int(*)(
int)) toupper);
64 inline std::string encodeForXML(
const std::string& in) {
66 typedef std::pair<std::string, std::string> CharsToEntities;
67 std::vector<CharsToEntities> cs2es;
68 cs2es.push_back(std::make_pair(
"&",
"&"));
69 cs2es.push_back(std::make_pair(
"<",
"<"));
70 cs2es.push_back(std::make_pair(
">",
">"));
71 for (std::vector<CharsToEntities>::const_iterator c2e = cs2es.begin(); c2e != cs2es.end(); ++c2e) {
72 std::string::size_type pos = -1;
73 while ( ( pos = out.find(c2e->first, pos + 1) ) != std::string::npos ) {
74 out.replace(pos, 1, c2e->second);
82 inline bool contains(
const std::string& s,
const std::string& sub) {
83 return s.find(sub) != std::string::npos;
87 inline bool startswith(
const std::string& s,
const std::string& sub) {
88 return s.find(sub) == 0;
92 inline bool endswith(
const std::string& s,
const std::string& sub) {
93 const size_t pos = s.find(sub);
94 return pos != std::string::npos && pos == (s.size()-sub.size());
99 inline std::string& iltrim(std::string& s) {
100 s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](
unsigned char c){ return !std::isspace(c); }));
106 inline std::string& irtrim(std::string& s) {
107 s.erase(std::find_if(s.rbegin(), s.rend(), [](
unsigned char c){ return !std::isspace(c); }).base(), s.end());
112 inline std::string& itrim(std::string& s) {
113 return iltrim(irtrim(s));
118 inline std::string ltrim(
const std::string& s) {
124 inline std::string rtrim(
const std::string& s) {
130 inline std::string trim(
const std::string& s) {
136 inline std::vector<std::string> split(
const std::string& s,
const std::string& sep) {
137 std::vector<std::string> dirs;
140 const size_t delim_pos = tmp.find(sep);
141 if (delim_pos == std::string::npos)
break;
142 const std::string dir = tmp.substr(0, delim_pos);
143 if (dir.length()) dirs.push_back(dir);
144 tmp.replace(0, delim_pos+1,
"");
146 if (tmp.length()) dirs.push_back(tmp);
153 inline std::vector<std::string> pathsplit(
const std::string& path) {
154 return split(path,
":");
Anonymous namespace to limit visibility.