File: StringUtil.cpp

package info (click to toggle)
pentobi 29.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,892 kB
  • sloc: cpp: 25,719; javascript: 875; xml: 40; makefile: 13; sh: 6
file content (87 lines) | stat: -rw-r--r-- 2,125 bytes parent folder | download | duplicates (2)
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
//-----------------------------------------------------------------------------
/** @file libboardgame_base/StringUtil.cpp
    @author Markus Enzenberger
    @copyright GNU General Public License version 3 or later */
//-----------------------------------------------------------------------------

#include "StringUtil.h"

#include <cctype>
#include <cmath>
#include <iomanip>

namespace libboardgame_base {

//-----------------------------------------------------------------------------

string get_letter_coord(unsigned i)
{
    string result;
    while (true)
    {
        result.insert(0, 1, char('a' + i % 26));
        i /= 26;
        if (i == 0)
            break;
        --i;
    }
    return result;
}

vector<string> split(const string& s, char separator)
{
    vector<string> result;
    string current;
    for (char c : s)
    {
        if (c == separator)
        {
            result.push_back(current);
            current.clear();
            continue;
        }
        current.push_back(c);
    }
    if (! current.empty() || ! result.empty())
        result.push_back(current);
    return result;
}

string time_to_string(double seconds, bool with_seconds_as_double)
{
    auto int_seconds = static_cast<int>(round(seconds));
    int hours = int_seconds / 3600;
    int_seconds -= hours * 3600;
    int minutes = int_seconds / 60;
    int_seconds -= minutes * 60;
    ostringstream s;
    s << setfill('0');
    if (hours > 0)
        s << hours << ':';
    s << setw(2) << minutes << ':' << setw(2) << int_seconds;
    if (with_seconds_as_double)
        s << " (" << seconds << ')';
    return s.str();
}

string to_lower(string s)
{
    for (auto& c : s)
        c = static_cast<char>(tolower(c));
    return s;
}

string trim(const string& s)
{
    string::size_type begin = 0;
    auto end = s.size();
    while (begin != end && isspace(s[begin]) != 0)
        ++begin;
    while (end > begin && isspace(s[end - 1]) != 0)
        --end;
    return s.substr(begin, end - begin);
}

//-----------------------------------------------------------------------------

} // namespace libboardgame_base