Skip to content

Commit

Permalink
Template on std::basic_string
Browse files Browse the repository at this point in the history
Signed-off-by: Jacob Perron <jacob@openrobotics.org>
  • Loading branch information
jacobperron committed Jun 11, 2019
1 parent 3fb4961 commit 9fe5c66
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
27 changes: 23 additions & 4 deletions include/rcpputils/find_and_replace.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#ifndef RCPPUTILS__FIND_AND_REPLACE_HPP_
#define RCPPUTILS__FIND_AND_REPLACE_HPP_

#include <memory>
#include <string>

namespace rcpputils
Expand All @@ -28,23 +29,41 @@ namespace rcpputils
* \return A copy of the input string with all instances of the string `find` replaced with the
* string `replace`.
*/
inline std::string
find_and_replace(const std::string & input, const std::string & find, const std::string & replace)
template<
class CharT,
class Traits = std::char_traits<CharT>,
class Allocator = std::allocator<CharT>
>
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)
{
std::string output = input;
std::basic_string<CharT, Traits, Allocator> output = input;
const std::size_t find_len = find.length();
const std::size_t replace_len = replace.length();
if (find == replace) {
return output;
}
if (0u == find_len) {
return output;
}
std::size_t pos = output.find(find);
while (pos != std::string::npos) {
while (pos != std::basic_string<CharT, Traits, Allocator>::npos) {
output.replace(pos, find_len, replace);
pos = output.find(find, pos + replace_len);
}
return output;
}

inline
std::string
find_and_replace(const std::string & input, const std::string & find, const std::string & replace)
{
return find_and_replace<char>(input, find, replace);
}

} // namespace rcpputils

#endif // RCPPUTILS__FIND_AND_REPLACE_HPP_
8 changes: 8 additions & 0 deletions test/test_find_and_replace.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,11 @@ TEST(test_find_and_replace, find_and_replace) {
EXPECT_EQ("bar", ret);
}
}

TEST(test_find_and_replace, find_and_replace_wstring) {
auto ret = rcpputils::find_and_replace(
std::wstring(L"foobar"),
std::wstring(L"foo"),
std::wstring(L"bar"));
EXPECT_EQ(std::wstring(L"barbar"), ret);
}

0 comments on commit 9fe5c66

Please sign in to comment.