Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 411e44a

Browse files
Fix implementation of String::replace(const String& find, const String& replace) when 'find' len is higher than 'replace' len
1 parent e4febf7 commit 411e44a

File tree

2 files changed

+13
-11
lines changed

2 files changed

+13
-11
lines changed

‎api/String.cpp‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -646,18 +646,22 @@ void String::replace(const String& find, const String& replace)
646646
readFrom = foundAt + replace.len;
647647
}
648648
} else if (diff < 0) {
649-
char *writeTo = buffer;
649+
unsignedint size = len; // compute size needed for result
650650
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
651-
unsigned int n = foundAt - readFrom;
652-
memcpy(writeTo, readFrom, n);
653-
writeTo += n;
654-
memcpy(writeTo, replace.buffer, replace.len);
655-
writeTo += replace.len;
656651
readFrom = foundAt + find.len;
657-
len += diff;
652+
diff = 0 - diff;
653+
size -= diff;
654+
}
655+
if (size == len) return;
656+
int index = len - 1;
657+
while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
658+
readFrom = buffer + index + find.len;
659+
memmove(readFrom - diff, readFrom, len - (readFrom - buffer));
660+
len -= diff;
661+
buffer[len] = 0;
662+
memcpy(buffer + index, replace.buffer, replace.len);
663+
index--;
658664
}
659-
if (writeTo != readFrom)
660-
strcpy(writeTo, readFrom);
661665
} else {
662666
unsigned int size = len; // compute size needed for result
663667
while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {

‎test/src/String/test_replace.cpp‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,4 @@ TEST_CASE ("Testing String::replace(String, String) substr 'find' smaller than '
5656
arduino::String str("Hello Arduino!");
5757
str.replace(arduino::String("ll"), arduino::String("111"));
5858
REQUIRE(strcmp(str.c_str(), "He111o Arduino!") == 0);
59-
//REQUIRE(strcmp("He11 Arduino!", "He11 Arduino!") == 0);
60-
//REQUIRE(str.startsWith("Hel1o") == 0);
6159
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /