source: rrlib_util/sStringUtils.h @ 139:804baa38d03b

Last change on this file since 139:804baa38d03b was 139:804baa38d03b, checked in by Jens Wettach <wettach@…>, 4 years ago

moved sStringUtils::Tokenize to string.h, replaced some functions of sStringUtils with corresponding functions in string.h and marked the old ones as deprecated

File size: 12.0 KB
Line 
1//
2// You received this file as part of RRLib
3// Robotics Research Library
4//
5// Copyright (C) Finroc GbR (finroc.org)
6//
7// This program is free software; you can redistribute it and/or modify
8// it under the terms of the GNU General Public License as published by
9// the Free Software Foundation; either version 2 of the License, or
10// (at your option) any later version.
11//
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15// GNU General Public License for more details.
16//
17// You should have received a copy of the GNU General Public License along
18// with this program; if not, write to the Free Software Foundation, Inc.,
19// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20//
21//----------------------------------------------------------------------
22/*!\file    rrlib/util/sStringUtils.h
23 *
24 * \author  Bernd Helge Schaefer
25 * \author  Jens Wettach
26 *
27 * \date    2005-11-15
28 *
29 * \brief   Contains static class sStringUtils
30 *
31 */
32//----------------------------------------------------------------------
33// Includes
34//----------------------------------------------------------------------
35#ifndef _rrlib_util_sStringUtils_h_
36#define _rrlib_util_sStringUtils_h_
37
38//C++ stl includes
39#include <vector>
40#include <cassert>
41#include <cstring>
42#include <sstream>
43#include <cstdio>
44#include <algorithm>
45#include <iterator>
46
47
48//----------------------------------------------------------------------
49// Namespace declaration
50//----------------------------------------------------------------------
51namespace rrlib
52{
53namespace util
54{
55/*!
56    Stream manipulator definition for reading a string from actual position within the stream up to the end of line.
57*/
58struct imanip
59{
60  std::istream& (*f)(std::istream&, std::string&);
61  std::string& str;
62
63  imanip(std::istream & (*ff)(std::istream&, std::string&), std::string& sstr) : f(ff), str(sstr)
64  {}
65}
66;
67
68/*!
69    Overloading of stream operator >> to be used with new stream manipulator \em imanip.
70*/
71template <class Ch, class Tr>
72std::basic_istream<Ch, Tr>& operator>>(std::basic_istream<Ch, Tr>& is, imanip m)
73{
74  return m.f(is, m.str);
75};
76
77
78/*!
79    Stream manipulator implementation for reading a string from actual position within the stream up to the end of line.
80*/
81inline std::istream& get_line(std::istream& fin, std::string& str)
82{
83  std::ostringstream ss;
84  char c;
85  fin.get(c);
86  while ((c == ' ' || c == '\t') && (c != '\n'))                                   // skip leading whitespace(s)
87  {
88    fin.get(c);
89  }
90  while (c != '\n' && !fin.eof())
91  {
92    //DEBUGMSG(DD_DEFAULT,DL_DEFAULT, "reading %c\n", c );
93    ss << c;
94    fin.get(c);
95  }
96  //    fin.ignore(0, '\n');   // skip end of line
97  str = ss.str();
98  if (fin.eof())
99  {
100    //DEBUGMSG(DD_DEFAULT,DL_DEFAULT, "---------------------------------------------------------------------------------->end of stream\n" );
101  }
102  return fin;
103}
104
105
106
107
108class sStringUtils
109{
110
111private:
112
113  static bool StringCompare(const std::string &left, const std::string &right)
114  {
115    for (std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit)
116      if (std::tolower(*lit) < std::tolower(*rit))
117        return true;
118      else if (std::tolower(*lit) > std::tolower(*rit))
119        return false;
120    if (left.size() < right.size())
121      return true;
122    return false;
123  }
124
125
126public:
127
128  static const char* Description()
129  {
130    return "sStringUtils";
131  }
132
133  static const size_t max_chars = 255;
134
135  /*!
136   * \brief Converts the input string to an upper case string.
137   *
138   * Note that if input and output string pointer are not the same, the
139   * caller needs to assure that for the output string at least as
140   * much bytes are allocated as the length of the input string.
141   * Otherwise a memory violation will occur.
142   *
143   * \param input_str The string to be converted to upper case.
144   * \param output_str Handle to the upper case string (May be the same as the input string for destructive mode of operation).
145   */
146  static void ToUpper(const char* input_str, char* output_str)
147  {
148    unsigned int num_chars = strlen(input_str);
149
150    if (num_chars > max_chars)
151    {
152      fprintf(stderr, "%s::ToUpper>> string length (%d) exceeds max chars (%zu)\n",
153              Description(), num_chars, max_chars);
154      fprintf(stderr, "Due to security reasons this is not permitted.\nOnly %zu chars will be converted to upper case.\n",
155              max_chars);
156      num_chars = max_chars;
157    }
158
159    for (unsigned int i = 0; i < num_chars; i++)
160    {
161      output_str [i] = toupper(input_str [i]);
162    }
163    output_str [num_chars] = '\0';
164  }
165
166  /*!
167   * \brief Converts the input string to an lower case string.
168   *
169   * For details see documentation of routine ToUpper().
170   */
171  static void ToLower(const char* input_str, char* output_str)
172  {
173    unsigned int num_chars = (strlen(input_str) < strlen(output_str) ? strlen(input_str) : strlen(output_str));
174
175    if (num_chars > max_chars)
176    {
177      fprintf(stderr, "%s::ToLower>> string length (%d) exceeds max chars (%zu)\n",
178              Description(), num_chars, max_chars);
179      fprintf(stderr, "Due to security reasons this is not permitted.\nOnly %zu chars will be converted to lower case.\n",
180              max_chars);
181      num_chars = max_chars;
182    }
183
184    for (unsigned int i = 0; i < num_chars; i++)
185    {
186      output_str [i] = tolower(input_str [i]);
187    }
188    output_str [num_chars] = '\0';
189  }
190
191  /*!
192   * \brief Removes brackets and spaces
193   */
194  static void RemoveBracketsAndSpaces(const char* input_str, char* output_str, const char replace_token = '_');
195
196  /*!
197   * \brief Splits a string into a list of tokes using the provided delimiter.
198   *
199   * \param str The string to be split up
200   * \param tokens The list of tokens
201   * \param The delimiter
202   */
203  static void Tokenize(const std::string& str,
204                       std::vector<std::string>& tokens,
205                       const std::string& delimiters) __attribute__((deprecated("USE rrlib::util::Tokenize() [rrlib/util/string.h] instead")));
206
207
208  /*!
209       * \brief Replaces a section of the current string by some other content.
210       *
211       * \param str The string whose content should be replaced
212       * \param target_token The part of the string that should  be replaced
213       * \param replace_token The token that should be placed in the string instead of the target_token
214       */
215  static void Replace(std::string &input_str, const char* target_token, const char* replace_token);
216
217  /*!
218       * \brief Replaces one character of the current string by an other char.
219       *
220       * \param str The string whose content should be replaced
221       * \param target_token The character of the string that should  be replaced
222       * \param replace_token The character that should be placed in the string instead of the target_token
223       */
224
225  static void Replace(char *input_str, char target_token, char replace_token);
226
227  static std::string ConstReplace(const std::string &input_str, const char* target_token, const char* replace_token);
228
229  /*!
230   * Stream manipulator implementation for reading a string from actual position within the stream up to the end of line.
231   * Uses function <get_line>, but provides normal stream manipulator interface.
232   *
233   * Example: input_stream >> sStringUtils::getline( word );
234   *
235   */
236  static imanip getline(std::string& str)
237  {
238    return imanip(get_line, str);
239  }
240
241
242  /*!
243   * \brief Replaces commata by points in the provided c string.
244   *
245   * \param str The c string in which all commata shall be replaced by points.
246   */
247  static void ReplaceCommasByPoints(char* str)
248  {
249    char comma [2];
250    memset(comma, 0, 2);
251    comma [0] = ',';
252    //    fprintf (stderr, "test str: %s\n", test);
253    char* temp_str = str;
254    for (unsigned int i = 0; i < strlen(str); i++)
255    {
256      if (strncmp(comma, temp_str, 1) == 0)
257      {
258        temp_str [0] = '.';
259        // fprintf (stderr, "replacing: %s\n", str);
260      }
261      temp_str++;
262    }
263  }
264
265  /*!
266   * \brief Trims whitespace at the front and the back of given string
267   *
268   */
269  static void TrimWhitespace(std::string &text) __attribute__((deprecated("USE rrlib::util::TrimWhitespace() [rrlib/util/string.h] instead")));
270
271  /*!
272   * \brief Removes multiple whitespaces in the given string
273   *
274   */
275  static void RemoveMultipleWhitespaces(std::string &text);
276
277  /*!
278     * \brief returns true if given element is first part of given text
279     */
280  static bool BeginsWith(const std::string& text, const std::string& element) __attribute__((deprecated("USE rrlib::util::StartsWith() [rrlib/util/string.h] instead")));
281
282  /*!
283     * \brief returns true if given element is last part of given text
284     */
285  static bool EndsWith(const std::string& text, const std::string& element) __attribute__((deprecated("USE rrlib::util::EndsWith() [rrlib/util/string.h] instead")));
286
287  /*!
288   * \brief Builds a list of strings from a list of character arrays.
289   */
290  static void BuildStringListFromCharArrays(std::vector <std::string>& name_list, const char* const* names, size_t number_of_names)
291  {
292    assert(names != NULL);
293    name_list.clear();
294    for (size_t i = 0; i < number_of_names; i++)
295    {
296      assert(names [i] != NULL);
297      name_list.push_back(names [i]);
298    }
299  }
300
301  static void BuildStringListFromCharArrays(std::vector <std::string>& name_list, const std::vector <const char*>& names)
302  {
303    name_list.clear();
304    for (size_t i = 0; i < names.size(); i++)
305    {
306      assert(names [i] != NULL);
307      name_list.push_back(names [i]);
308    }
309  }
310
311  /*!
312   * \brief Returns true if string equals "true" or "1".
313   * \param s string to be checked
314   */
315  static bool StringToBool(std::string s);
316
317
318  /*!
319   * \brief Converting object to std::string and returning the string
320   * \param object to be converted
321   */
322  template <class T>
323  static std::string StringOf(const T& object)
324  {
325    std::ostringstream os;
326    os << object;
327    return (os.str());
328  }
329
330  /*!
331   * \brief Converting object to std::string
332   * \param object to be converted, string is stored in s
333   */
334  template <class T>
335  static void StringOf(const T& object, std::string & s)
336  {
337    std::ostringstream os;
338    os << object;
339    s = os.str();
340  }
341  /*!
342   * \brief Converting a std::string representing a hexadecimal number into a decimal number
343   * \param string representing hexadecimal number
344   */
345
346  template<class T>
347  static T HexStringToDecNumber(std::string str)
348  {
349    std::istringstream iss(str);
350    T result = 0;
351    iss >> std::hex >> result;
352    return result;
353  }
354
355
356  /*!
357   * \brief Enclosing string with the given prefix and suffix
358   * \param input string, prefix, and suffix
359   * \return the enclosed string
360   */
361  static std::string EncloseString(const char* string, const char* prefix, const char* suffix)
362  {
363    return std::string(std::string(prefix) + std::string(string) + std::string(suffix));
364  }
365
366  /*!
367     * \brief Enclosing string with the given prefix and suffix
368     * \param output string, where the enclosed string will be stored, input string, prefix, and suffix
369     */
370  static bool EncloseString(std::string &output_string, const char* input_string, const char* prefix, const char* suffix)
371  {
372    output_string = std::string(prefix) + std::string(input_string) + std::string(suffix);
373    return true;
374  }
375
376
377  static bool SortStringVector(std::vector<std::string> &vec)
378  {
379    std::sort(vec.begin(), vec.end(), StringCompare);
380    return true;
381  }
382
383  static int FindStringInArray(const char* str, char*const* str_array, size_t num_str_in_array)
384  {
385    char*const* descr_begin(&str_array[0]);
386    char*const* descr_end(&str_array[0] + num_str_in_array);
387    char*const* pos = std::find(descr_begin, descr_end, str);
388    if (pos != descr_end)
389      return std::distance(descr_begin, pos);
390    else
391      return -1;
392  }
393
394};
395
396//----------------------------------------------------------------------
397// End of namespace declaration
398//----------------------------------------------------------------------
399}; // namespace util
400}; // namespace rrlib
401#endif
402
Note: See TracBrowser for help on using the repository browser.