File: StringUtil.cpp

package info (click to toggle)
bornagain 23.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 103,936 kB
  • sloc: cpp: 423,131; python: 40,997; javascript: 11,167; awk: 630; sh: 318; ruby: 173; xml: 130; makefile: 51; ansic: 24
file content (191 lines) | stat: -rw-r--r-- 5,644 bytes parent folder | download
1
2
3
4
5
6
7
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//  ************************************************************************************************
//
//  BornAgain: simulate and fit reflection and scattering
//
//! @file      Base/Util/StringUtil.cpp
//! @brief     Implements a few helper functions.
//!
//! @homepage  http://www.bornagainproject.org
//! @license   GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2018
//! @authors   Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
//  ************************************************************************************************

#include "Base/Util/StringUtil.h"
#include "Base/Util/Assert.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <charconv>
#include <chrono>
#include <iomanip>
#include <iterator>
#include <ranges>
#include <regex>
#include <sstream>

//! Returns token vector obtained by splitting string at delimiters.
std::vector<std::string> Base::String::split(const std::string& text, const std::string& delimiter)
{
    if (text.empty())
        return {};
    std::vector<std::string> result;
    size_t pos = 0;
    while (pos != std::string::npos) {
        size_t next_pos = text.find(delimiter, pos);
        if (next_pos == std::string::npos) {
            result.push_back(text.substr(pos));
            break;
        }
        result.push_back(text.substr(pos, next_pos - pos));
        pos = next_pos + delimiter.length();
    }
    return result;
}

void Base::String::replaceItemsFromString(std::string& text, const std::vector<std::string>& items,
                                          const std::string& replacement)
{
    for (const auto& item : items) {
        size_t pos = 0;
        while ((pos = text.find(item, pos)) != std::string::npos) {
            text.replace(pos, item.length(), replacement);
            pos += replacement.length();
        }
    }
}

std::string Base::String::join(const std::vector<std::string>& joinable, const std::string& joint)
{
    std::string result;
    size_t n = joinable.size();
    if (n == 0)
        return result;
    for (size_t i = 0; i < n - 1; ++i)
        result += joinable[i] + joint;
    result += joinable[n - 1];
    return result;
}

std::string Base::String::to_lower(std::string text)
{

    std::ranges::transform(text, text.begin(), [](unsigned char c) { return std::tolower(c); });
    return text;
}

bool Base::String::to_int(const std::string& str, int* result)
{
    const char* first = str.data() + str.find_first_not_of(' ');
    const char* last = str.data() + str.size();
    int _result = 0;
    auto [p, ec] = std::from_chars(first, last, _result);

    if (ec != std::errc())
        return false;

    if (p != last) {
        // not all was consumed. Check whether only space characters left
        const size_t pos = p - str.data();
        const auto hasNonSpaceLeft = str.find_first_not_of(' ', pos) != std::string::npos;
        if (hasNonSpaceLeft)
            return false;
    }

    if (result != nullptr)
        *result = _result;
    return true;
}

bool Base::String::to_double(const std::string& str, double* result)
{
    errno = 0;
    char* end{};
    const char* p = str.c_str();
    *result = std::strtod(p, &end);
    if (end == p) // no digits found
        return false;
    if (errno != 0) {
        errno = 0;
        return false;
    }
    return true;
}

std::string Base::String::trim(const std::string& str, const std::string& whitespace)
{
    const auto strBegin = str.find_first_not_of(whitespace);

    if (strBegin == std::string::npos)
        return "";

    const auto strEnd = str.find_last_not_of(whitespace);
    const auto strRange = strEnd - strBegin + 1;

    return str.substr(strBegin, strRange);
}

std::string Base::String::trimFront(const std::string& str, const std::string& whitespace)
{
    const auto strBegin = str.find_first_not_of(whitespace);

    if (strBegin == std::string::npos)
        return "";

    return str.substr(strBegin);
}

bool Base::String::startsWith(const std::string& str, const std::string& substr)
{
    return str.rfind(substr, 0) == 0;
}

std::vector<int> Base::String::expandNumberList(const std::string& pattern)
{
    std::vector<int> result;

    for (const std::string& word : split(trim(pattern), ",")) {

        std::vector<std::string> parts = split(trim(word), "-");
        if (parts.empty())
            throw std::runtime_error("invalid number list");
        if (parts.size() > 2)
            throw std::runtime_error("invalid number list");
        int i0;
        bool ok = to_int(parts[0], &i0);
        if (!ok)
            throw std::runtime_error("invalid number list");
        if (parts.size() == 1)
            result.push_back(i0);
        else {
            ASSERT(parts.size() == 2);
            int i1;
            ok = to_int(parts[1], &i1);
            if (!ok)
                throw std::runtime_error("invalid number list");
            for (int j = i0; j <= i1; ++j)
                result.push_back(j);
        }
    }

    return result;
}

std::vector<double> Base::String::parse_doubles(const std::string& str)
{
    std::vector<double> result;
    std::istringstream iss(str);
    iss.imbue(std::locale::classic());
    std::copy(std::istream_iterator<double>(iss), std::istream_iterator<double>(),
              back_inserter(result));
    if (result.empty()) {
        std::string out = str;
        if (out.size() > 10) {
            out.resize(10, ' ');
            out += " ...";
        }
        throw std::runtime_error("Found '" + out + "' while expecting a floating-point number");
    }
    return result;
}