Skip to content

Commit c2de99d

Browse files
committed
fix replace on empty strings
1 parent f38e935 commit c2de99d

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

pystring.cpp

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -967,31 +967,44 @@ typedef int Py_ssize_t;
967967
//////////////////////////////////////////////////////////////////////////////////////////////
968968
///
969969
///
970+
970971
std::string replace( const std::string & str, const std::string & oldstr, const std::string & newstr, int count )
971972
{
972973
int sofar = 0;
973974
int cursor = 0;
974975
std::string s( str );
975976

976977
std::string::size_type oldlen = oldstr.size(), newlen = newstr.size();
978+
979+
cursor = find( s, oldstr, cursor );
977980

978-
while ( ( cursor = find( s, oldstr, cursor ) ) != -1 )
981+
while ( cursor != -1 && cursor <= (int)s.size() )
979982
{
980983
if ( count > -1 && sofar >= count )
981984
{
982985
break;
983986
}
984987

985988
s.replace( cursor, oldlen, newstr );
986-
987989
cursor += (int) newlen;
990+
991+
if ( oldlen != 0)
992+
{
993+
cursor = find( s, oldstr, cursor );
994+
}
995+
else
996+
{
997+
++cursor;
998+
}
999+
9881000
++sofar;
9891001
}
9901002

9911003
return s;
9921004

9931005
}
994-
1006+
1007+
9951008
//////////////////////////////////////////////////////////////////////////////////////////////
9961009
///
9971010
///

test.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,16 @@ PYSTRING_ADD_TEST(pystring, rfind)
9494
PYSTRING_CHECK_EQUAL(pystring::rfind("abcabcabc", "abc", 6, 8), -1);
9595
}
9696

97+
PYSTRING_ADD_TEST(pystring, replace)
98+
{
99+
PYSTRING_CHECK_EQUAL(pystring::replace("abcdef", "foo", "bar"), "abcdef");
100+
PYSTRING_CHECK_EQUAL(pystring::replace("abcdef", "ab", "cd"), "cdcdef");
101+
PYSTRING_CHECK_EQUAL(pystring::replace("abcdef", "ab", ""), "cdef");
102+
PYSTRING_CHECK_EQUAL(pystring::replace("abcabc", "ab", ""), "cc");
103+
PYSTRING_CHECK_EQUAL(pystring::replace("abcdef", "", ""), "abcdef");
104+
PYSTRING_CHECK_EQUAL(pystring::replace("abcdef", "", "."), ".a.b.c.d.e.f.");
105+
}
106+
97107
PYSTRING_ADD_TEST(pystring, slice)
98108
{
99109
PYSTRING_CHECK_EQUAL(pystring::slice(""), "");

0 commit comments

Comments
 (0)