From a4bf234df17da7919590d2e1a6dda5ab0f4f0859 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Karas?= Date: Fri, 22 Sep 2023 21:28:03 +0200 Subject: [PATCH 1/2] add ReplaceString test when search phrase is on the start and the end --- Tests/src/StringUtils.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/src/StringUtils.cpp b/Tests/src/StringUtils.cpp index 95abd5bc3..dde2cb83c 100644 --- a/Tests/src/StringUtils.cpp +++ b/Tests/src/StringUtils.cpp @@ -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"); } From 4c742eda74a25b8c83617ccda6e8142212d7a7d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Karas?= Date: Fri, 22 Sep 2023 21:31:21 +0200 Subject: [PATCH 2/2] rewrite ReplaceString utility, fix for case when search is on the string boundary --- libosmscout/src/osmscout/util/String.cpp | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/libosmscout/src/osmscout/util/String.cpp b/libosmscout/src/osmscout/util/String.cpp index b241e9946..42a34bdeb 100644 --- a/libosmscout/src/osmscout/util/String.cpp +++ b/libosmscout/src/osmscout/util/String.cpp @@ -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> SplitStringToPair(const std::string& str,