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

#include <algorithm>
#include <numeric>
#include <string>
Paul's avatar
Paul committed
7
#include <sstream>
Paul's avatar
Paul committed
8

Paul's avatar
Paul committed
9
namespace migraph {
Paul's avatar
Paul committed
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

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
template <class Range>
Paul's avatar
Paul committed
69
inline std::string to_string_range(const Range& r)
Paul's avatar
Paul committed
70
71
72
73
74
{
    std::stringstream ss;
    if(!r.empty())
    {
        ss << r.front();
Paul's avatar
Paul committed
75
        std::for_each(std::next(r.begin()), r.end(), [&](auto&& x) { ss << ", " << x; });
Paul's avatar
Paul committed
76
77
78
79
    }
    return ss.str();
}

Paul's avatar
Paul committed
80
81
82
83
84
85
86
87
template<class T>
inline std::string to_string(const T& x)
{
    std::stringstream ss;
    ss << x;
    return ss.str();
}

Paul's avatar
Paul committed
88
} // namespace migraph
Paul's avatar
Paul committed
89

Paul's avatar
Paul committed
90
#endif