/ src / common / utils / string_utils.h
string_utils.h
 1  #pragma once
 2  
 3  #include <string_view>
 4  #include <string>
 5  #include <algorithm>
 6  
 7  template<typename CharT>
 8  struct default_trim_arg
 9  {
10  };
11  
12  template<>
13  struct default_trim_arg<char>
14  {
15      static inline constexpr std::string_view value = " \t\r\n";
16  };
17  
18  template<>
19  struct default_trim_arg<wchar_t>
20  {
21      static inline constexpr std::wstring_view value = L" \t\r\n";
22  };
23  
24  template<typename CharT>
25  inline std::basic_string_view<CharT> left_trim(std::basic_string_view<CharT> s,
26                                                 const std::basic_string_view<CharT> chars_to_trim = default_trim_arg<CharT>::value)
27  {
28      s.remove_prefix(std::min<size_t>(s.find_first_not_of(chars_to_trim), size(s)));
29      return s;
30  }
31  
32  template<typename CharT>
33  inline std::basic_string_view<CharT> right_trim(std::basic_string_view<CharT> s,
34                                                  const std::basic_string_view<CharT> chars_to_trim = default_trim_arg<CharT>::value)
35  {
36      s.remove_suffix(std::min<size_t>(size(s) - s.find_last_not_of(chars_to_trim) - 1, size(s)));
37      return s;
38  }
39  
40  template<typename CharT>
41  inline std::basic_string_view<CharT> trim(std::basic_string_view<CharT> s,
42                                            const std::basic_string_view<CharT> chars_to_trim = default_trim_arg<CharT>::value)
43  {
44      return left_trim(right_trim(s, chars_to_trim), chars_to_trim);
45  }
46  
47  template<typename CharT>
48  inline void replace_chars(std::basic_string<CharT>& s,
49                            const std::basic_string_view<CharT> chars_to_replace,
50                            const CharT replacement_char)
51  {
52      for (const CharT c : chars_to_replace)
53      {
54          std::replace(begin(s), end(s), c, replacement_char);
55      }
56  }
57  
58  inline std::string unwide(const std::wstring& wide)
59  {
60      std::string result(wide.length(), 0);
61      std::transform(begin(wide), end(wide), result.begin(), [](const wchar_t c) {
62          return static_cast<char>(c);
63      });
64      return result;
65  }