Skip to content

Commit

Permalink
Merge pull request #1507 from Karry/replace-string-fix
Browse files Browse the repository at this point in the history
fix ReplaceString utility
  • Loading branch information
Framstag authored Sep 24, 2023
2 parents 2d9a24f + 4c742ed commit a744ff0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
2 changes: 2 additions & 0 deletions Tests/src/StringUtils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -325,4 +325,6 @@ TEST_CASE("String replace")
REQUIRE(osmscout::ReplaceString("", "a", "b").empty());
REQUIRE(osmscout::ReplaceString("abc", "", "b")=="abc");
REQUIRE(osmscout::ReplaceString("abcabc", "a", "A")=="AbcAbc");
REQUIRE(osmscout::ReplaceString("abcdef", "ef", "X")=="abcdX");
REQUIRE(osmscout::ReplaceString("abcdef", "ab", "X")=="Xcdef");
}
23 changes: 15 additions & 8 deletions libosmscout/src/osmscout/util/String.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -432,16 +432,23 @@ namespace osmscout {
if (search.empty()) {
return in;
}
auto arr=SplitString(in, search);
std::ostringstream buff;
for (auto it=arr.begin(); it!=arr.end();) {
buff << *it;
++it;
if (it!=arr.end()) {
buff << replacement;

std::ostringstream result;
std::string remaining=in;

while (!remaining.empty()) {
std::string::size_type pos = remaining.find(search);
if (pos == std::string::npos) {
result << remaining;
break;
} else {
result << remaining.substr(0, pos);
result << replacement;
remaining.erase(0, pos + search.length());
}
}
return buff.str();

return result.str();
}

std::optional<std::pair<std::string,std::string>> SplitStringToPair(const std::string& str,
Expand Down

0 comments on commit a744ff0

Please sign in to comment.