Skip to content

Commit 87f90ee

Browse files
author
Joel Allred
committed
Add replace_all string utility
Utility to search and replace strings inside a string.
1 parent 7823d9c commit 87f90ee

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/util/string_utils.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,3 +148,24 @@ std::string escape(const std::string &s)
148148

149149
return result;
150150
}
151+
152+
/// Replace all occurrences of a string inside a string
153+
/// \param [out] str: string to search
154+
/// \param from: string to replace
155+
/// \param to: string to replace with
156+
/// Copyright notice:
157+
/// Attributed to Gauthier Boaglio
158+
/// Source: https://stackoverflow.com/a/24315631/7501486
159+
/// Used under MIT license
160+
void replace_all(
161+
std::string &str,
162+
const std::string &from,
163+
const std::string &to)
164+
{
165+
size_t start_pos = 0;
166+
while((start_pos = str.find(from, start_pos)) != std::string::npos)
167+
{
168+
str.replace(start_pos, from.length(), to);
169+
start_pos += to.length();
170+
}
171+
}

src/util/string_utils.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,6 @@ Stream &join_strings(
6767
/// programming language.
6868
std::string escape(const std::string &);
6969

70+
void replace_all(std::string &, const std::string &, const std::string &);
71+
7072
#endif

0 commit comments

Comments
 (0)