Skip to content

Instantly share code, notes, and snippets.

@mtrencseni
Created April 8, 2023 13:59
Show Gist options
  • Save mtrencseni/cb6f268e3c65033ddca78ffb80d3578c to your computer and use it in GitHub Desktop.
Save mtrencseni/cb6f268e3c65033ddca78ffb80d3578c to your computer and use it in GitHub Desktop.
#ifndef __UTILS_HPP__
#define __UTILS_HPP__
#include <map>
#include <regex>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
void trim(string& str)
{
auto is_space = [](char c) { return std::isspace(static_cast<unsigned char>(c)); };
str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::not_fn(is_space)));
str.erase(std::find_if(str.rbegin(), str.rend(), std::not_fn(is_space)).base(), str.end());
}
bool startswith(string_view s, string_view prefix)
{
return s.find(prefix, 0) == 0;
}
vector<string> split(const string& s, char delim)
{
vector<string> result;
stringstream ss(s);
string item;
while (getline(ss, item, delim))
result.push_back(item);
return result;
}
string join(const string& delimiter, const vector<string>& strings)
{
if (strings.empty()) {
return "";
}
ostringstream oss;
copy(strings.begin(), strings.end() - 1, ostream_iterator<string>(oss, delimiter.c_str()));
oss << strings.back();
return oss.str();
}
typedef map<string, string> Dict;
Dict parse_dict(const string& dict_str)
{
Dict result;
regex dict_pattern(R"(\s*'([^']+)'\s*:\s*'([^']+)'\s*)");
smatch matches;
auto search_start = dict_str.begin();
while (regex_search(search_start, dict_str.end(), matches, dict_pattern)) {
result[matches[1].str()] = matches[2].str();
search_start = matches[0].second;
}
return result;
}
string serialize_dict(const Dict& d)
{
std::ostringstream oss;
oss << "{";
for (auto it = d.begin(); it != d.end();) {
oss << '\'' << it->first << "': '" << it->second << '\'';
if (++it != d.end())
oss << ", ";
}
oss << "}";
return oss.str();
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment