Skip to content

Instantly share code, notes, and snippets.

@satoruhiga
Created May 22, 2012 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satoruhiga/2768887 to your computer and use it in GitHub Desktop.
Save satoruhiga/2768887 to your computer and use it in GitHub Desktop.
text_util.h
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
namespace text_util
{
typedef std::map<std::string, std::string> param;
inline std::string fmt(const std::string& t, const param& kv)
{
std::string tpl = t;
param::const_iterator it = kv.begin();
while (it != kv.end())
{
std::string from;
from = "{{" + (*it).first + "}}";
const std::string &to = (*it).second;
std::string::size_type pos = 0;
while(pos = tpl.find(from, pos), pos != std::string::npos)
{
tpl.replace(pos, from.length(), to);
pos += to.length();
}
it++;
}
return tpl;
}
inline std::string join(const std::vector<std::string> &v, const std::string& sep)
{
std::string ret;
for (size_t i = 0; i < v.size(); i++)
{
ret += v[i];
if (i < v.size() - 1) ret += sep;
}
return ret;
}
inline std::string trim(const std::string &src)
{
std::string ret;
std::string::size_type pos = 0;
while (true)
{
if (!std::isspace(src[pos]))
{
ret = src.substr(pos);
break;
}
pos++;
}
std::string::size_type rpos = ret.size() - 1;
while (true)
{
if (!std::isspace(ret[rpos]))
{
ret = ret.substr(0, rpos + 1);
break;
}
rpos--;
}
return ret;
}
inline std::vector<std::string> split(const std::string &src, const std::string &deim, bool ignoreEmpty = true, bool trim = true)
{
std::vector<std::string> ret;
if (deim.empty())
{
ret.push_back(src);
return ret;
}
std::string::const_iterator substart = src.begin(), subend;
while (true)
{
subend = search(substart, src.end(), deim.begin(), deim.end());
std::string sub(substart, subend);
if (trim)
{
sub = text_util::trim(sub);
}
if (!ignoreEmpty || !sub.empty())
{
ret.push_back(sub);
}
if (subend == src.end())
{
break;
}
substart = subend + deim.size();
}
return ret;
}
template <typename T>
inline std::string str(const T& v)
{
std::stringstream ss;
ss << v;
return ss.str();
}
}
#if 0
using namespace std;
int main(int argc, char *argv[])
{
// fmt, str
text_util::param p;
p["the"] = "a";
p["number"] = text_util::str(42);
cout << text_util::fmt("replace {{the}} string {{number}}", p) << endl;
// trim
cout << "'" << text_util::trim(" trim string ") << "'" << endl;
// split
vector<string> ss = text_util::split("this is a test", " ", true, true);
for (int i = 0; i < ss.size(); i++)
cout << ss[i] << "/";
cout << endl;
// join
cout << text_util::join(ss, ", ") << endl;
return 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment