String.cpp 1.75 KB
Newer Older
1
2
3
4
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

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
#include "String.hpp"

namespace AMDiS
{
  /// convert all characters in a string to upper case
  std::string to_upper(std::string input)
  {
    for (auto& c : input)
      c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    return input;
  }

  /// convert all characters in a string to upper case
  std::string to_lower(std::string input)
  {
    for (auto& c : input)
      c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
    return input;
  }

  /// trim a string from the left
  std::string& ltrim(std::string& str)
  {
    auto it =  std::find_if(str.begin(), str.end(), [](char ch)
    {
      return !std::isspace<char>(ch, std::locale::classic());
    });
    str.erase(str.begin() , it);
    return str;
  }

  /// trim a string from the right
  std::string& rtrim(std::string& str)
  {
    auto it =  std::find_if(str.rbegin(), str.rend(), [](char ch)
    {
      return !std::isspace<char>(ch, std::locale::classic());
    });
    str.erase(it.base(), str.end());
    return str;
  }

  /// trim a string from both sides
  std::string& trim(std::string& str)
  {
    return ltrim(rtrim(str));
  }

  /// trim a (copy of the) string from both sides
  std::string trim_copy(std::string const& str)
  {
    auto s = str;
    return trim(s);
  }

  /// Replace all occurences of substring `from` with `to` in source `str`.
  void replaceAll(std::string& str, std::string const& from, std::string const& to)
  {
    if (from.empty())
      return;

    typename std::string::size_type start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != std::string::npos)
    {
      str.replace(start_pos, from.length(), to);
      start_pos += to.length();
    }
  }

} // end namspace AMDiS