Mana
Loading...
Searching...
No Matches
stringutils.cpp
Go to the documentation of this file.
1/*
2 * The Mana Client
3 * Copyright (C) 2007-2009 The Mana World Development Team
4 * Copyright (C) 2009-2012 The Mana Developers
5 *
6 * This file is part of The Mana Client.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 */
21
22#include "utils/stringutils.h"
23
24#include <cstring>
25#include <algorithm>
26#include <cstdarg>
27#include <cstdio>
28
29std::string &trim(std::string &str)
30{
31 std::string::size_type pos = str.find_last_not_of(' ');
32 if (pos != std::string::npos)
33 {
34 str.erase(pos + 1);
35 pos = str.find_first_not_of(' ');
36
37 if (pos != std::string::npos)
38 str.erase(0, pos);
39 }
40 else
41 {
42 // There is nothing else but whitespace in the string
43 str.clear();
44 }
45 return str;
46}
47
48std::string &toLower(std::string &str)
49{
50 std::transform(str.begin(), str.end(), str.begin(), tolower);
51 return str;
52}
53
54std::string &toUpper(std::string &str)
55{
56 std::transform(str.begin(), str.end(), str.begin(), toupper);
57 return str;
58}
59
60unsigned int atox(const std::string &str)
61{
62 unsigned int value;
63 sscanf(str.c_str(), "0x%06x", &value);
64
65 return value;
66}
67
68const char *ipToString(int address)
69{
70 static char asciiIP[16];
71
72 snprintf(asciiIP, 16, "%i.%i.%i.%i",
73 (unsigned char)(address),
74 (unsigned char)(address >> 8),
75 (unsigned char)(address >> 16),
76 (unsigned char)(address >> 24));
77
78 return asciiIP;
79}
80
81std::string strprintf(char const *format, ...)
82{
83 char buf[256];
84 va_list args;
85 va_start(args, format);
86 int nb = vsnprintf(buf, 256, format, args);
87 va_end(args);
88 if (nb < 256)
89 {
90 return buf;
91 }
92 // The static size was not big enough, try again with a dynamic allocation.
93 ++nb; // Add 1 for the null terminator.
94
95 std::string res(nb, char());
96 va_start(args, format);
97 vsnprintf(res.data(), nb, format, args);
98 va_end(args);
99 return res;
100}
101
102std::string &replaceCharacters(std::string &str,
103 std::string_view chars,
104 char replacement)
105{
106 for (auto &c : str)
107 {
108 if (chars.find(c) != std::string::npos)
109 c = replacement;
110 }
111 return str;
112}
113
114std::string &removeColors(std::string &msg)
115{
116 auto pos = msg.find("##");
117 while (pos != std::string::npos && msg.length() - pos >= 3)
118 {
119 msg.erase(pos, 3);
120 pos = msg.find("##", pos);
121 }
122 return msg;
123}
124
125bool isWordSeparator(char chr)
126{
127 return (chr == ' ' || chr == ',' || chr == '.' || chr == '"');
128}
129
130std::string findSameSubstring(const std::string &str1,
131 const std::string &str2)
132{
133 int minLength = str1.length() > str2.length() ? str2.length() : str1.length();
134 for (int f = 0; f < minLength; f ++)
135 {
136 if (str1.at(f) != str2.at(f))
137 {
138 return str1.substr(0, f);
139 }
140 }
141 return str1.substr(0, minLength);
142}
143
144bool getBoolFromString(std::string text, bool def)
145{
146 toLower(trim(text));
147 if (text == "true" || text == "1" || text == "on" || text == "yes" || text == "y")
148 return true;
149 if (text == "false" || text == "0" || text == "off" || text == "no" || text == "n")
150 return false;
151
152 return def;
153}
154
155// Overload for std::vector<int> to parse comma-separated integers
156void fromString(const char *str, std::vector<int> &value)
157{
158 value.clear();
159
160 const char *p = str;
161 while (*p)
162 {
163 while (*p == ' ' || *p == ',')
164 ++p; // skip spaces and commas
165 if (!*p)
166 break;
167 char *end = nullptr;
168 int v = static_cast<int>(strtol(p, &end, 10));
169 if (end != p)
170 {
171 value.push_back(v);
172 p = end;
173 }
174 else
175 {
176 ++p; // skip invalid character to avoid infinite loop
177 }
178 }
179}
180
181std::string autocomplete(const std::vector<std::string> &candidates,
182 std::string base)
183{
184 auto i = candidates.begin();
185 toLower(base);
186 std::string newName;
187
188 while (i != candidates.end())
189 {
190 if (!i->empty())
191 {
192 std::string name = *i;
193 toLower(name);
194
195 std::string::size_type pos = name.find(base, 0);
196 if (pos == 0)
197 {
198 if (!newName.empty())
199 {
200 toLower(newName);
201 newName = findSameSubstring(name, newName);
202 }
203 else
204 {
205 newName = *i;
206 }
207 }
208 }
209
210 ++i;
211 }
212
213 return newName;
214}
215
216std::string normalize(const std::string &name)
217{
218 std::string normalized = name;
219 return toLower(trim(normalized));
220}
221
222std::string getDirectoryFromURL(const std::string &url)
223{
224 std::string directory = url;
225
226 // Parse out any "http://", "ftp://", etc...
227 size_t pos = directory.find("://");
228 if (pos != std::string::npos)
229 directory.erase(0, pos + 3);
230
231 // Replace characters which are not valid or difficult in file system paths
232 replaceCharacters(directory, ":*?\"<>| ", '_');
233
234 // Replace ".." (double dots) with "_" to avoid directory traversal.
235 pos = directory.find("..");
236 while (pos != std::string::npos)
237 {
238 directory.replace(pos, 2, "_");
239 pos = directory.find("..");
240 }
241
242 return directory;
243}
244
245std::string join(const std::vector<std::string> &strings, const char *separator)
246{
247 std::string result;
248 if (auto i = strings.begin(), e = strings.end(); i != e)
249 {
250 result += *i++;
251 for (; i != e; ++i)
252 result.append(separator).append(*i);
253 }
254 return result;
255}
void fromString(const char *str, std::vector< int > &value)
std::string & replaceCharacters(std::string &str, std::string_view chars, char replacement)
Replaces a set of characters with another character.
unsigned int atox(const std::string &str)
Converts an ascii hexidecimal string to an integer.
bool isWordSeparator(char chr)
Tells wether the character is a word separator.
std::string & toUpper(std::string &str)
Converts the given string to upper case.
std::string getDirectoryFromURL(const std::string &url)
Derives a directory from the given URL, stripping the schema and replacing certain invalid characters...
bool getBoolFromString(std::string text, bool def)
Returns a bool value depending on the given string value.
std::string & toLower(std::string &str)
Converts the given string to lower case.
std::string strprintf(char const *format,...)
A safe version of sprintf that returns a std::string of the result.
std::string join(const std::vector< std::string > &strings, const char *separator)
Joins a vector of strings into one string, separated by the given separator.
std::string & trim(std::string &str)
Trims spaces off the end and the beginning of the given string.
std::string findSameSubstring(const std::string &str1, const std::string &str2)
const char * ipToString(int address)
Converts the given IP address to a string.
std::string normalize(const std::string &name)
Normalize a string, which means lowercase and trim it.
std::string autocomplete(const std::vector< std::string > &candidates, std::string base)
Returns the most approaching string of base from candidates.
std::string & removeColors(std::string &msg)
Removes colors from a string.