Optimize the performance of StringUtils.replace

bug 36583, from Chris Hyzer

git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/lang/trunk@279977 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Stephen Colebourne 2005-09-10 09:29:48 +00:00
parent 7240ef6dec
commit 7c818a9f22
3 changed files with 27 additions and 6 deletions

View File

@ -226,6 +226,9 @@ limitations under the License.
<contributor>
<name>Oliver Heger</name>
</contributor>
<contributor>
<name>Chris Hyzer</name>
</contributor>
<contributor>
<name>Marc Johnson</name>
</contributor>

View File

@ -111,6 +111,7 @@
* @author Al Chou
* @author Michael Davey
* @author Reuben Sivan
* @author Chris Hyzer
* @since 1.0
* @version $Id$
*/
@ -2956,19 +2957,25 @@ public static String replace(String text, String repl, String with) {
* <code>null</code> if null String input
*/
public static String replace(String text, String repl, String with, int max) {
if (text == null || isEmpty(repl) || with == null || max == 0) {
if (isEmpty(text) || isEmpty(repl) || with == null || max == 0) {
return text;
}
StringBuffer buf = new StringBuffer(text.length());
int start = 0, end = 0;
while ((end = text.indexOf(repl, start)) != -1) {
int start = 0;
int end = text.indexOf(repl, start);
if (end == -1) {
return text;
}
int increase = with.length() - repl.length();
increase = (increase < 0 ? 0 : increase);
increase *= (max < 0 ? 16 : (max > 64 ? 64 : max));
StringBuffer buf = new StringBuffer(text.length() + increase);
while (end != -1) {
buf.append(text.substring(start, end)).append(with);
start = end + repl.length();
if (--max == 0) {
break;
}
end = text.indexOf(repl, start);
}
buf.append(text.substring(start));
return buf.toString();

View File

@ -804,12 +804,23 @@ public void testReplace_StringStringStringInt() {
assertEquals(null, StringUtils.replace(null, "any", null, 2));
assertEquals(null, StringUtils.replace(null, "any", "any", 2));
assertEquals("", StringUtils.replace("", null, null, 2));
assertEquals("", StringUtils.replace("", null, "any", 2));
assertEquals("", StringUtils.replace("", "any", null, 2));
assertEquals("", StringUtils.replace("", "any", "any", 2));
String str = new String(new char[] {'o', 'o', 'f', 'o', 'o'});
assertSame(str, StringUtils.replace(str, "x", "", -1));
assertEquals("f", StringUtils.replace("oofoo", "o", "", -1));
assertEquals("oofoo", StringUtils.replace("oofoo", "o", "", 0));
assertEquals("ofoo", StringUtils.replace("oofoo", "o", "", 1));
assertEquals("foo", StringUtils.replace("oofoo", "o", "", 2));
assertEquals("fo", StringUtils.replace("oofoo", "o", "", 3));
assertEquals("f", StringUtils.replace("oofoo", "o", "", 4));
assertEquals("f", StringUtils.replace("oofoo", "o", "", -5));
assertEquals("f", StringUtils.replace("oofoo", "o", "", 1000));
}
public void testReplaceOnce_StringStringString() {