Skip to content

Commit 6c1671d

Browse files
committed
Add in-place replaceAll method to StrUtils
1 parent 276c322 commit 6c1671d

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

Common/Utils/include/CommonUtils/StringUtils.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,9 @@ struct Str {
146146
return s.str();
147147
}
148148

149+
// replace all occurencies of from by to, return count
150+
static int replaceAll(std::string& s, const std::string& from, const std::string& to);
151+
149152
// generate random string of given length, suitable for file names
150153
static std::string getRandomString(int length);
151154

Common/Utils/src/StringUtils.cxx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,19 @@ std::vector<std::string> Str::tokenize(const std::string& src, char delim, bool
3434
return tokens;
3535
}
3636

37+
// replace all occurencies of from by to, return count
38+
int Str::replaceAll(std::string& s, const std::string& from, const std::string& to)
39+
{
40+
int count = 0;
41+
size_t pos = 0;
42+
while ((pos = s.find(from, pos)) != std::string::npos) {
43+
s.replace(pos, from.length(), to);
44+
pos += to.length(); // Handles case where 'to' is a substring of 'from'
45+
count++;
46+
}
47+
return count;
48+
}
49+
3750
// generate random string of given lenght, suitable for file names
3851
std::string Str::getRandomString(int lenght)
3952
{

0 commit comments

Comments
 (0)