Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/util/String.cc @ 1477

Last change on this file since 1477 was 1477, checked in by landauf, 16 years ago
  • small char-length tweaking for my system (because i have to show the shell)
  • fixed bug causing orxonox to loop forever when loading the config file (you'll like this, felix)
File size: 14.1 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) 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, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      Benjamin Grauer
26 *
27 */
28
29#include "String.h"
30
31#include <cctype>
32#include <iostream>
33
34/**
35    @brief Removes all whitespaces from a string.
36    @param str The string to strip
37*/
38void strip(std::string* str)
39{
40    unsigned int pos;
41    while ((pos = (*str).find(" ")) < (*str).length())
42        (*str).erase(pos, 1);
43    while ((pos = (*str).find("\t")) < (*str).length())
44        (*str).erase(pos, 1);
45}
46
47/**
48    @brief Returns a copy of a string without whitespaces.
49    @param str The string to strip
50    @return The stripped line
51*/
52std::string getStripped(const std::string& str)
53{
54    std::string output = std::string(str);
55    strip(&output);
56    return output;
57}
58
59/**
60    @brief Returns a copy of a string without trailing whitespaces.
61    @param str The string
62    @return The modified copy
63*/
64std::string removeTrailingWhitespaces(const std::string& str)
65{
66    unsigned int pos1 = 0;
67    int pos2 = str.size() - 1;
68    for (; pos1 < str.size() && (str[pos1] == ' ' || str[pos1] == '\t' || str[pos1] == '\n'); pos1++);
69    for (; pos2 > 0          && (str[pos2] == ' ' || str[pos2] == '\t' || str[pos2] == '\n'); pos2--);
70    return str.substr(pos1, pos2 - pos1 + 1);
71}
72
73/**
74    @brief Returns the position of the next quote in the string, starting with start.
75    @param str The string
76    @param start The startposition
77    @return The position of the next quote (std::string::npos if there is no next quote)
78*/
79unsigned int getNextQuote(const std::string& str, unsigned int start)
80{
81    unsigned int quote = start - 1;
82
83    while ((quote = str.find('\"', quote + 1)) != std::string::npos)
84    {
85        unsigned int backslash = quote;
86        unsigned int numbackslashes = 0;
87        for (; backslash > 0; backslash--, numbackslashes++)
88            if (str[backslash - 1] != '\\')
89                break;
90
91        if (numbackslashes % 2 == 0)
92            break;
93    }
94
95    return quote;
96}
97
98/**
99    @brief Returns true if pos is between two quotes.
100    @param str The string
101    @param pos The position to check
102    @return True if pos is between two quotes
103*/
104bool isBetweenQuotes(const std::string& str, unsigned int pos)
105{
106    if (pos == std::string::npos)
107        return false;
108
109    unsigned int quotecount = 0;
110    unsigned int quote = 0;
111    while ((quote = getNextQuote(str, quote)) < pos)
112    {
113        quotecount++;
114        quote++;
115    }
116
117    if (quote == std::string::npos)
118        return false;
119
120    return ((quotecount % 2) == 1);
121}
122
123/**
124    @brief Returns true if the string contains something like '..."between quotes"...'
125    @param The string
126    @return True if there is something between quotes
127*/
128bool hasStringBetweenQuotes(const std::string& str)
129{
130    unsigned int pos1 = getNextQuote(str, 0);
131    unsigned int pos2 = getNextQuote(str, pos1 + 1);
132    return (pos1 != std::string::npos && pos2 != std::string::npos && pos2 > pos1 + 1);
133}
134
135/**
136    @brief If the string contains something like '..."between quotes"...' then 'between quotes' gets returned (without quotes).
137    @param The string
138    @param The string between the quotes
139*/
140std::string getStringBetweenQuotes(const std::string& str)
141{
142    unsigned int pos1 = getNextQuote(str, 0);
143    unsigned int pos2 = getNextQuote(str, pos1 + 1);
144    if (pos1 != std::string::npos && pos2 != std::string::npos)
145        return str.substr(pos1, pos2 - pos1 + 1);
146    else
147        return "";
148}
149
150/**
151    @brief Removes enclosing quotes if available.
152    @brief str The string to strip
153    @return The string with removed quotes
154*/
155std::string stripEnclosingQuotes(const std::string& str)
156{
157    unsigned int start = std::string::npos;
158    unsigned int end = 0;
159
160    for (unsigned int pos = 0; (pos < str.size()) && (pos < std::string::npos); pos++)
161    {
162        if (str[pos] == '"')
163        {
164            start = pos;
165            break;
166        }
167
168        if ((str[pos] != ' ') && (str[pos] != '\t') && (str[pos] != '\n'))
169            return str;
170    }
171
172    for (unsigned int pos = str.size() - 1; pos < std::string::npos; pos--)
173    {
174        if (str[pos] == '"')
175        {
176            end = pos;
177            break;
178        }
179
180        if ((str[pos] != ' ') && (str[pos] != '\t') && (str[pos] != '\n'))
181            return str;
182    }
183
184    if ((start != std::string::npos) && (end != 0))
185        return str.substr(start + 1, end - start - 1);
186    else
187        return str;
188}
189
190/**
191    @brief Removes enclosing {braces}.
192    @param str The string to strip
193    @return The striped string
194*/
195std::string stripEnclosingBraces(const std::string& str)
196{
197    std::string output = str;
198
199    while (output.size() >= 2 && output[0] == '{' && output[output.size() - 1] == '}')
200        output = output.substr(1, output.size() - 2);
201
202    return output;
203}
204
205/**
206    @brief Determines if a string in is a comment.
207    @param str The string to check
208    @return True = it's a comment
209
210    A comment is defined by a leading '#', '%', ';' or '//'.
211*/
212bool isComment(const std::string& str)
213{
214    // Strip the line, whitespaces are disturbing
215    std::string teststring = getStripped(str);
216
217    // There are four possible comment-symbols:
218    //  1) #comment in script-language style
219    //  2) %comment in matlab style
220    //  3) ;comment in unreal tournament config-file style
221    //  4) //comment in code style
222    if (teststring.size() >= 2)
223    {
224        if (teststring[0] == '#' || teststring[0] == '%' || teststring[0] == ';' || (teststring[0] == '/' && teststring[1] == '/'))
225            return true;
226    }
227    else if (teststring.size() == 1)
228    {
229        if (teststring[0] == '#' || teststring[0] == '%' || teststring[0] == ';')
230            return true;
231    }
232
233    return false;
234}
235
236/**
237    @brief Determines if a string is empty (contains only whitespaces).
238    @param str The string to check
239    @return True = it's empty
240*/
241bool isEmpty(const std::string& str)
242{
243    std::string temp = getStripped(str);
244    return ((temp == "") || (temp.size() == 0));
245}
246
247/**
248    @brief Determines if a string contains only numbers and maximal one '.'.
249    @param str The string to check
250    @return True = it's a number
251*/
252bool isNumeric(const std::string& str)
253{
254    bool foundPoint = false;
255
256    for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
257    {
258        if (((*it) < '0' || (*it) > '9'))
259        {
260            if ((*it) != '.' && !foundPoint)
261                foundPoint = true;
262            else
263                return false;
264        }
265    }
266
267    return true;
268}
269
270std::string addSlashes(const std::string& str)
271{
272    std::string output = str;
273
274    for (unsigned int pos = 0; (pos = output.find('\\', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\\\"); }
275    for (unsigned int pos = 0; (pos = output.find('\n', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\n"); }
276    for (unsigned int pos = 0; (pos = output.find('\t', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\t"); }
277    for (unsigned int pos = 0; (pos = output.find('\v', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\v"); }
278    for (unsigned int pos = 0; (pos = output.find('\b', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\b"); }
279    for (unsigned int pos = 0; (pos = output.find('\r', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\r"); }
280    for (unsigned int pos = 0; (pos = output.find('\f', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\f"); }
281    for (unsigned int pos = 0; (pos = output.find('\a', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\a"); }
282    for (unsigned int pos = 0; (pos = output.find('"', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\\""); }
283    for (unsigned int pos = 0; (pos = output.find('\0', pos)) < std::string::npos; pos += 2) { output.replace(pos, 1, "\\0"); }
284
285    return output;
286}
287
288std::string removeSlashes(const std::string& str)
289{
290    if (str.size() <= 1)
291        return str;
292
293    std::string output = "";
294    for (unsigned int pos = 0; pos < str.size() - 1; )
295    {
296        if (str[pos] == '\\')
297        {
298            if (str[pos + 1] == '\\') { output += '\\'; pos += 2; continue; }
299            else if (str[pos + 1] == 'n') { output += '\n'; pos += 2; continue; }
300            else if (str[pos + 1] == 't') { output += '\t'; pos += 2; continue; }
301            else if (str[pos + 1] == 'v') { output += '\v'; pos += 2; continue; }
302            else if (str[pos + 1] == 'b') { output += '\b'; pos += 2; continue; }
303            else if (str[pos + 1] == 'r') { output += '\r'; pos += 2; continue; }
304            else if (str[pos + 1] == 'f') { output += '\f'; pos += 2; continue; }
305            else if (str[pos + 1] == 'a') { output += '\a'; pos += 2; continue; }
306            else if (str[pos + 1] == '"') { output += '"'; pos += 2; continue; }
307            else if (str[pos + 1] == '0') { output += '\0'; pos += 2; continue; }
308        }
309        output += str[pos];
310        pos++;
311        if (pos == str.size() - 1)
312            output += str[pos];
313    }
314
315    return output;
316}
317
318/**
319    @brief Replaces each char between A and Z with its lowercase equivalent.
320    @param str The string to convert
321*/
322void lowercase(std::string* str)
323{
324    for (unsigned int i = 0; i < str->size(); ++i)
325    {
326        (*str)[i] = (char)tolower((*str)[i]);
327    }
328}
329
330/**
331    @brief Returns a copy of the given string without uppercase chars.
332    @param str The string
333    @return The copy
334*/
335std::string getLowercase(const std::string& str)
336{
337    std::string output = std::string(str);
338    lowercase(&output);
339    return output;
340}
341
342/**
343    @brief Replaces each char between a and z with its uppercase equivalent.
344    @param str The string to convert
345*/
346void uppercase(std::string* str)
347{
348    for (unsigned int i = 0; i < str->size(); ++i)
349    {
350        (*str)[i] = (char)toupper((*str)[i]);
351    }
352}
353
354/**
355    @brief Returns a copy of the given string without lowercase chars.
356    @param str The string
357    @return The copy
358*/
359std::string getUppercase(const std::string& str)
360{
361    std::string output = std::string(str);
362    uppercase(&output);
363    return output;
364}
365
366/**
367    @brief compares two strings without ignoring the case
368    @param s1 first string
369    @param s2 second string
370*/
371int nocaseCmp(const std::string& s1, const std::string& s2)
372{
373    std::string::const_iterator it1=s1.begin();
374    std::string::const_iterator it2=s2.begin();
375
376    //stop when either string's end has been reached
377    while ( (it1!=s1.end()) && (it2!=s2.end()) )
378    {
379        if(::toupper(*it1) != ::toupper(*it2)) //letters differ?
380            // return -1 to indicate smaller than, 1 otherwise
381            return (::toupper(*it1)  < ::toupper(*it2)) ? -1 : 1;
382        //proceed to the next character in each string
383        ++it1;
384        ++it2;
385    }
386    size_t size1=s1.size(), size2=s2.size();// cache lengths
387    //return -1,0 or 1 according to strings' lengths
388    if (size1==size2)
389        return 0;
390    return (size1<size2) ? -1 : 1;
391}
392
393
394/**
395    @brief compares two strings without ignoring the case
396    @param s1 first string
397    @param s2 second string
398    @param len how far from the beginning to start.
399*/
400int nocaseCmp(const std::string& s1, const std::string& s2, unsigned int len)
401{
402    if (len == 0)
403        return 0;
404    std::string::const_iterator it1=s1.begin();
405    std::string::const_iterator it2=s2.begin();
406
407    //stop when either string's end has been reached
408    while ( (it1!=s1.end()) && (it2!=s2.end()) && len-- > 0)
409    {
410        if(::toupper(*it1) != ::toupper(*it2)) //letters differ?
411            // return -1 to indicate smaller than, 1 otherwise
412            return (::toupper(*it1)  < ::toupper(*it2)) ? -1 : 1;
413        //proceed to the next character in each string
414        ++it1;
415        ++it2;
416    }
417    return 0;
418}
419
420/**
421    @brief Returns true if the string contains a comment, introduced by #, %, ; or //.
422    @param str The string
423    @return True if the string contains a comment
424*/
425bool hasComment(const std::string& str)
426{
427    return (getCommentPosition(str) != std::string::npos);
428}
429
430/**
431    @brief If the string contains a comment, the comment gets returned (including the comment symbol), an empty string otherwise.
432    @param str The string
433    @return The comment
434*/
435std::string getComment(const std::string& str)
436{
437    return str.substr(getCommentPosition(str));
438}
439
440/**
441    @brief If the string contains a comment, the position of the comment-symbol gets returned, std::string::npos otherwise.
442    @param str The string
443    @return The position
444*/
445unsigned int getCommentPosition(const std::string& str)
446{
447    return getNextCommentPosition(str, 0);
448}
449
450/**
451    @brief Returns the position of the next comment-symbol, starting with start.
452    @param str The string
453    @param start The startposition
454    @return The position
455*/
456unsigned int getNextCommentPosition(const std::string& str, unsigned int start)
457{
458    for (unsigned int i = start; i < str.size(); i++)
459        if (isComment(str.substr(i)))
460            return i;
461
462    return std::string::npos;
463}
Note: See TracBrowser for help on using the repository browser.