rcpputils  master
C++ API providing common utilities and data structures.
find_and_replace.hpp
Go to the documentation of this file.
1 // Copyright 2019 Open Source Robotics Foundation, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
19 #ifndef RCPPUTILS__FIND_AND_REPLACE_HPP_
20 #define RCPPUTILS__FIND_AND_REPLACE_HPP_
21 
22 #include <memory>
23 #include <string>
24 
25 namespace rcpputils
26 {
27 
29 
36 template<
37  class CharT,
38  class Traits = std::char_traits<CharT>,
39  class Allocator = std::allocator<CharT>
40 >
46 {
48  const std::size_t find_len = find.length();
49  const std::size_t replace_len = replace.length();
50  if (find == replace) {
51  return output;
52  }
53  if (0u == find_len) {
54  return output;
55  }
56  std::size_t pos = output.find(find);
58  output.replace(pos, find_len, replace);
59  pos = output.find(find, pos + replace_len);
60  }
61  return output;
62 }
63 
64 namespace detail
65 {
66 template<typename CharT, std::size_t Length>
68 normalize_to_basic_string(const CharT (& char_string)[Length])
69 {
70  return std::basic_string<CharT>(char_string);
71 }
72 
73 template<typename StringLikeT>
74 StringLikeT &&
75 normalize_to_basic_string(StringLikeT && string_like)
76 {
77  return string_like;
78 }
79 } // namespace detail
80 
82 
89 template<typename InputT, typename FindT, typename ReplaceT>
90 auto
92  InputT && input,
93  FindT && find,
94  ReplaceT && replace)
95 {
96  auto input_str = detail::normalize_to_basic_string(input);
97  return find_and_replace<typename decltype(input_str)::value_type>(
98  input_str,
99  detail::normalize_to_basic_string(find),
100  detail::normalize_to_basic_string(replace));
101 }
102 
103 } // namespace rcpputils
104 
105 #endif // RCPPUTILS__FIND_AND_REPLACE_HPP_
std::basic_string
rcpputils
Definition: asserts.hpp:37
std::basic_string::find
T find(T... args)
rcpputils::find_and_replace
std::basic_string< CharT, Traits, Allocator > find_and_replace(const std::basic_string< CharT, Traits, Allocator > &input, const std::basic_string< CharT, Traits, Allocator > &find, const std::basic_string< CharT, Traits, Allocator > &replace)
Find and replace all instances of a string with another string.
Definition: find_and_replace.hpp:42
std::basic_string::replace
T replace(T... args)
std::char_traits
std::allocator
std::size_t