stringutils.hpp 1.95 KB
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
#ifndef GUARD_RTGLIB_STRINGUTILS_HPP
#define GUARD_RTGLIB_STRINGUTILS_HPP

#include <algorithm>
#include <numeric>
#include <string>
Paul's avatar
Paul committed
7
#include <sstream>
Paul's avatar
Paul committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

namespace rtg {

inline std::string
replace_string(std::string subject, const std::string& search, const std::string& replace)
{
    size_t pos = 0;
    while((pos = subject.find(search, pos)) != std::string::npos)
    {
        subject.replace(pos, search.length(), replace);
        pos += replace.length();
    }
    return subject;
}

inline bool ends_with(const std::string& value, const std::string& suffix)
{
    if(suffix.size() > value.size())
        return false;
    else
        return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin());
}

template <class Strings>
inline std::string join_strings(Strings strings, std::string delim)
{
    auto it = strings.begin();
    if(it == strings.end())
        return "";

    auto nit = std::next(it);
    return std::accumulate(
        nit, strings.end(), *it, [&](std::string x, std::string y) { return x + delim + y; });
}

template <class F>
inline std::string transform_string(std::string s, F f)
{
    std::transform(s.begin(), s.end(), s.begin(), f);
    return s;
}

inline std::string to_upper(std::string s) { return transform_string(std::move(s), ::toupper); }

inline bool starts_with(const std::string& value, const std::string& prefix)
{
    if(prefix.size() > value.size())
        return false;
    else
        return std::equal(prefix.begin(), prefix.end(), value.begin());
}

inline std::string remove_prefix(std::string s, std::string prefix)
{
    if(starts_with(s, prefix))
        return s.substr(prefix.length());
    else
        return s;
}

Paul's avatar
Paul committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
template<class Range>
inline std::string to_string(const Range& r)
{
    std::stringstream ss;
    if(!r.empty())
    {
        ss << r.front();
        std::for_each(++r.begin(), r.end(), [&](auto&& x)
        {
            ss << ", " << x;
        });
    }
    return ss.str();
}

Paul's avatar
Paul committed
83
84
85
} // namespace rtg

#endif