1 //-----------------------------------------------------------------------------
2 /** @file libboardgame_base/StringUtil.cpp
3     @author Markus Enzenberger
4     @copyright GNU General Public License version 3 or later */
5 //-----------------------------------------------------------------------------
6 
7 #include "StringUtil.h"
8 
9 #include <cctype>
10 #include <cmath>
11 #include <iomanip>
12 
13 namespace libboardgame_base {
14 
15 //-----------------------------------------------------------------------------
16 
17 template<>
from_string(const string & s,string & t)18 bool from_string(const string& s, string& t)
19 {
20     t = s;
21     return true;
22 }
23 
get_letter_coord(unsigned i)24 string get_letter_coord(unsigned i)
25 {
26     string result;
27     while (true)
28     {
29         result.insert(0, 1, char('a' + i % 26));
30         i /= 26;
31         if (i == 0)
32             break;
33         --i;
34     }
35     return result;
36 }
37 
split(const string & s,char separator)38 vector<string> split(const string& s, char separator)
39 {
40     vector<string> result;
41     string current;
42     for (char c : s)
43     {
44         if (c == separator)
45         {
46             result.push_back(current);
47             current.clear();
48             continue;
49         }
50         current.push_back(c);
51     }
52     if (! current.empty() || ! result.empty())
53         result.push_back(current);
54     return result;
55 }
56 
time_to_string(double seconds,bool with_seconds_as_double)57 string time_to_string(double seconds, bool with_seconds_as_double)
58 {
59     auto int_seconds = static_cast<int>(round(seconds));
60     int hours = int_seconds / 3600;
61     int_seconds -= hours * 3600;
62     int minutes = int_seconds / 60;
63     int_seconds -= minutes * 60;
64     ostringstream s;
65     s << setfill('0');
66     if (hours > 0)
67         s << hours << ':';
68     s << setw(2) << minutes << ':' << setw(2) << int_seconds;
69     if (with_seconds_as_double)
70         s << " (" << seconds << ')';
71     return s.str();
72 }
73 
to_lower(string s)74 string to_lower(string s)
75 {
76     for (auto& c : s)
77         c = static_cast<char>(tolower(c));
78     return s;
79 }
80 
trim(const string & s)81 string trim(const string& s)
82 {
83     string::size_type begin = 0;
84     auto end = s.size();
85     while (begin != end && isspace(s[begin]) != 0)
86         ++begin;
87     while (end > begin && isspace(s[end - 1]) != 0)
88         --end;
89     return s.substr(begin, end - begin);
90 }
91 
92 //----------------------------------------------------------------------------
93 
94 } // namespace libboardgame_base
95