From 3a0ac1e14ac6f7bf42eeaed3686c08ed889c5e1f Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Wed, 15 Jan 2025 02:19:13 +0100 Subject: [PATCH] Fix wxString::BeforeFirst() when "rest" is the string itself This didn't work correctly before, but there doesn't seem to be any good reason to not allow this, as it allows to naturally extract some leading prefix from a string and it also already worked for BeforeLast(), so make it work for BeforeFirst() too. --- interface/wx/string.h | 4 +++- src/common/string.cpp | 6 ++++-- tests/strings/strings.cpp | 8 ++++++++ 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/interface/wx/string.h b/interface/wx/string.h index 6dae9f25e5..9ed9359386 100644 --- a/interface/wx/string.h +++ b/interface/wx/string.h @@ -1153,7 +1153,9 @@ public: is returned by AfterFirst() but it is more efficient to use this output parameter if both the "before" and "after" parts are needed than calling both functions one after the other. This parameter is - available in wxWidgets version 2.9.2 and later only. + available in wxWidgets version 2.9.2 and later only. Since + wxWidgets 3.3.0, this parameter can be equal to the string on which + this function is called. @return Part of the string before the first occurrence of @a ch. */ wxString BeforeFirst(wxUniChar ch, wxString *rest = nullptr) const; diff --git a/src/common/string.cpp b/src/common/string.cpp index c530ffc053..6c11296622 100644 --- a/src/common/string.cpp +++ b/src/common/string.cpp @@ -1127,20 +1127,22 @@ wxString wxString::Left(size_t nCount) const // (returns the whole string if ch not found) wxString wxString::BeforeFirst(wxUniChar ch, wxString *rest) const { + wxString ret; int iPos = Find(ch); if ( iPos == wxNOT_FOUND ) { - iPos = length(); + ret = *this; if ( rest ) rest->clear(); } else { + ret.assign(*this, 0, iPos); if ( rest ) rest->assign(*this, iPos + 1, npos); } - return wxString(*this, 0, iPos); + return ret; } /// get all characters before the last occurrence of ch diff --git a/tests/strings/strings.cpp b/tests/strings/strings.cpp index 724fe1a19c..034531ade7 100644 --- a/tests/strings/strings.cpp +++ b/tests/strings/strings.cpp @@ -1127,6 +1127,10 @@ TEST_CASE("StringBeforeAndAfter", "[wxString]") CHECK( s.BeforeFirst('!', &r) == s ); CHECK( r == "" ); + const wxString phrase("Two words apart"); + r = phrase; + CHECK( r.BeforeFirst(' ', &r) == "Two" ); + CHECK( r == "words apart" ); CHECK( s.BeforeLast('=', &r) == FIRST_PART wxT("=") MIDDLE_PART ); CHECK( r == LAST_PART ); @@ -1134,6 +1138,10 @@ TEST_CASE("StringBeforeAndAfter", "[wxString]") CHECK( s.BeforeLast('!', &r) == "" ); CHECK( r == s ); + r = phrase; + CHECK( r.BeforeLast(' ', &r) == "Two words" ); + CHECK( r == "apart" ); + CHECK( s.AfterFirst('=') == MIDDLE_PART wxT("=") LAST_PART ); CHECK( s.AfterFirst('!') == "" );