classlib: fix String.replace, add optimizations for some corner cases

Fix #932
This commit is contained in:
Alexey Andreev 2024-07-18 18:51:42 +02:00
parent 8889b63df7
commit 13a959ce67
2 changed files with 31 additions and 13 deletions

View File

@ -501,6 +501,19 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
} }
public String replace(TCharSequence target, TCharSequence replacement) { public String replace(TCharSequence target, TCharSequence replacement) {
if (target == replacement) {
return (String) (Object) this;
} else if (target.isEmpty()) {
var sb = new StringBuilder();
for (var i = 0; i < length(); ++i) {
sb.append(replacement);
sb.append(charAt(i));
}
sb.append(replacement);
return sb.toString();
} else if (target.length() == 1 && replacement.length() == 1) {
return (String) (Object) replace(target.charAt(0), replacement.charAt(0));
} else {
var sb = new StringBuilder(); var sb = new StringBuilder();
int sz = length() - target.length(); int sz = length() - target.length();
int i = 0; int i = 0;
@ -516,8 +529,10 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
i += target.length() - 1; i += target.length() - 1;
} }
sb.append(substring(i)); sb.append(substring(i));
return sb.toString(); return sb.toString();
} }
}
public TString trim() { public TString trim() {
int lower = 0; int lower = 0;

View File

@ -197,6 +197,9 @@ public class StringTest {
@Test @Test
public void sequenceReplaced() { public void sequenceReplaced() {
assertEquals("ba", "aaa".replace("aa", "b")); assertEquals("ba", "aaa".replace("aa", "b"));
assertEquals("xaxaxax", "aaa".replace("", "x"));
assertEquals("axc", "abc".replace("b", "x"));
assertEquals("abc", "abc".replace("bc", "bc"));
} }
@Test @Test