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('!') == "" );