mirror of
https://github.com/konsoletyper/teavm.git
synced 2024-11-21 01:00:54 +08:00
classlib: fix String.replace, add optimizations for some corner cases
Fix #932
This commit is contained in:
parent
8889b63df7
commit
13a959ce67
@ -501,22 +501,37 @@ public class TString extends TObject implements TSerializable, TComparable<TStri
|
||||
}
|
||||
|
||||
public String replace(TCharSequence target, TCharSequence replacement) {
|
||||
var sb = new StringBuilder();
|
||||
int sz = length() - target.length();
|
||||
int i = 0;
|
||||
outer:
|
||||
for (; i <= sz; ++i) {
|
||||
for (int j = 0; j < target.length(); ++j) {
|
||||
if (charAt(i + j) != target.charAt(j)) {
|
||||
sb.append(charAt(i));
|
||||
continue outer;
|
||||
}
|
||||
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);
|
||||
i += target.length() - 1;
|
||||
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();
|
||||
int sz = length() - target.length();
|
||||
int i = 0;
|
||||
outer:
|
||||
for (; i <= sz; ++i) {
|
||||
for (int j = 0; j < target.length(); ++j) {
|
||||
if (charAt(i + j) != target.charAt(j)) {
|
||||
sb.append(charAt(i));
|
||||
continue outer;
|
||||
}
|
||||
}
|
||||
sb.append(replacement);
|
||||
i += target.length() - 1;
|
||||
}
|
||||
sb.append(substring(i));
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
sb.append(substring(i));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public TString trim() {
|
||||
|
@ -197,6 +197,9 @@ public class StringTest {
|
||||
@Test
|
||||
public void sequenceReplaced() {
|
||||
assertEquals("ba", "aaa".replace("aa", "b"));
|
||||
assertEquals("xaxaxax", "aaa".replace("", "x"));
|
||||
assertEquals("axc", "abc".replace("b", "x"));
|
||||
assertEquals("abc", "abc".replace("bc", "bc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
Loading…
Reference in New Issue
Block a user