Showing results for stringutils replace
Search instead for stringutilsreplace

The String.replace() method you linked to takes two char values, so it only ever replaces on character with another (possibly multiple times, 'though).

The StringUtils.replace() method on the other hand takes String values as the search string and replacement, so it can replace longer substrings.

The comparable method in Java would be replaceAll(). replaceAll() is likely to be slower than the StringUtils method, because it supports regular expressions and thus introduces the overhead of compiling the search string first and running a regex search.

Note that Java 5 introduced String.replace(CharSequence, CharSequence) which does the same thing as StringUtils.replace(String,String) (except that it throws a NullPointerException if any of its arguments are null). Note that CharSequence is an interface implemented by String, so you can use plain old String objects here.

Answer from Joachim Sauer on Stack Overflow
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-release › org › apache › commons › lang3 › StringUtils.html
StringUtils (Apache Commons Lang 3.11 API)
Since: 2.5 · public static String appendIfMissing(String str, CharSequence suffix, CharSequence... suffixes) Appends the suffix to the end of the string if the string does not already end with any of the suffixes. StringUtils.appendIfMissing(null, null) = null StringUtils.appendIfMissing("abc", ...
Top answer
1 of 6
18

The String.replace() method you linked to takes two char values, so it only ever replaces on character with another (possibly multiple times, 'though).

The StringUtils.replace() method on the other hand takes String values as the search string and replacement, so it can replace longer substrings.

The comparable method in Java would be replaceAll(). replaceAll() is likely to be slower than the StringUtils method, because it supports regular expressions and thus introduces the overhead of compiling the search string first and running a regex search.

Note that Java 5 introduced String.replace(CharSequence, CharSequence) which does the same thing as StringUtils.replace(String,String) (except that it throws a NullPointerException if any of its arguments are null). Note that CharSequence is an interface implemented by String, so you can use plain old String objects here.

2 of 6
3
public class Compare {

    public static void main(String[] args) {
        StringUtils.isAlphanumeric(""); // Overhead of static class initialization for StringUtils
        String key = "0 abcdefghijklmno" + Character.toString('\n') + Character.toString('\r');

        String key1 = replace1(key);
        String key2 = replace2(key);
    }


    private static String replace1(String key) {
        long start = System.nanoTime();
        key = StringUtils.replaceChars(key, ' ', '_');
        key = StringUtils.replaceChars(key, '\n', '_');
        key = StringUtils.replaceChars(key, '\r', '_');
        long end = System.nanoTime() - start;
        System.out.println("Time taken : " + end);
        return key;
    }

    public static String replace2(String word) {
        long start = System.nanoTime();
        char[] charArr = word.toCharArray();

        int length = charArr.length;
        for (int i = 0; i < length; i++) {
            if (charArr[i] == ' ' || charArr[i] == '\n' || charArr[i] == '\r') {
                charArr[i] = '_';
            }
        }

        String temp = new String(charArr);
        long end = System.nanoTime() - start;
        System.out.println("Time taken : " + end);
        return temp;
    }
}

Time taken : 6400

Time taken : 5888

Times are almost the same!

I've edited the code to drop out overheads of replace2 which were not because of JDK implementation.

🌐
Educative
educative.io › answers › what-is-the-stringutilsreplace-method-in-java
What is the StringUtils.replace() method in Java?
In Java, replace() is a static method of the StringUtils class which is used to replace the search string with a replacement string. The method optionally accepts the first maximum number of matches of the search string to be replaced in the ...
🌐
Baeldung
baeldung.com › home › java › java string › remove or replace part of a string in java
Remove or Replace Part of a String in Java| Baeldung
June 15, 2024 - String master = "Hello World Baeldung!"; String target = "Baeldung"; String replacement = "Java"; String processed = StringUtils.replace(master, target, replacement); assertTrue(processed.contains(replacement));
🌐
GitHub
github.com › spring-projects › spring-data-mongodb › issues › 3613
Use StringUtils.replace(…) instead of String.replaceAll(…) for mapKeyDotReplacement · Issue #3613 · spring-projects/spring-data-mongodb
March 29, 2021 - * * @param source * @return */ protected String potentiallyUnescapeMapKey(String source) { return mapKeyDotReplacement == null ? source : source.replaceAll(mapKeyDotReplacement, "\\."); } Suggestion: Use org.springframework.util.StringUtils#replace or org.apache.commons.lang3.StringUtils#replace(java.lang.String, java.lang.String, java.lang.String) to replace dots instead.
Published   Mar 29, 2021
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.9 › org › apache › commons › lang3 › RegExUtils.html
RegExUtils (Apache Commons Lang 3.9 API)
Unlike in the replacePattern(String, String, String) method, the Pattern.DOTALL option is NOT automatically added. To use the DOTALL option prepend "(?s)" to the regex. DOTALL is also known as single-line mode in Perl. StringUtils.replaceAll(null, *, *) = null StringUtils.replaceAll("any", (String) null, *) = "any" StringUtils.replaceAll("any", *, null) = "any" StringUtils.replaceAll("", "", "zzz") = "zzz" StringUtils.replaceAll("", ".*", "zzz") = "zzz" StringUtils.replaceAll("", ".+", "zzz") = "" StringUtils.replaceAll("abc", "", "ZZ") = "ZZaZZbZZcZZ" StringUtils.replaceAll("<__>\n<__>", "<.*
🌐
jOOQ
blog.jooq.org › benchmarking-jdk-string-replace-vs-apache-commons-stringutils-replace
Benchmarking JDK String.replace() vs Apache Commons StringUtils.replace() – Java, SQL and jOOQ.
October 16, 2017 - static final String escape(Object val, Context&lt;?&gt; context) { String result = val.toString(); if (needsBackslashEscaping(context.configuration())) result = result.replace(&quot;\\&quot;, &quot;\\\\&quot;); return result.replace(&quot;'&quot;, &quot;''&quot;); } We’re always escaping apostrophes by doubling them, and in some databases (e.g. MySQL), we often have to escape backslashes as well (unfortunately, not all ORMs seem to do this or even be aware of this MySQL “feature”). Unfortunately as well, despite heavy use of Apache Commons Lang’s StringUtils.replace() in jOOQ’s internals, every now and then a String.replace(CharSequence) sneaks in, because it’s just so convenient to write.
🌐
Tabnine
tabnine.com › home page › code › java › org.apache.commons.lang.stringutils
org.apache.commons.lang.StringUtils.replace java code examples | Tabnine
Replaces all occurrences of a String within another String. A null reference passed to this method is a no-op. StringUtils.replace(null, *, *) = null StringUtils.replace("", *, *) = "" StringUtils.replace("any", null, *) = "any" StringUtils...
Find elsewhere
Top answer
1 of 5
66

In modern Java, this is not the case anymore. String.replace was improved in Java-9 moving from regular expression to StringBuilder, and was improved even more in Java-13 moving to direct allocation of the target byte[] array calculating its exact size in advance. Thanks to internal JDK features used, like the ability to allocate an uninitialized array, ability to access String coder and ability to use private String constructor which avoids copying, it's unlikely that current implementation can be beaten by a third-party implementation.

Here are my benchmarking results for your test using JDK 8, JDK 9 and JDK 13 (caliper:0.5-rc1; commons-lang3:3.9)

Java 8 (4x slower indeed):

 0% Scenario{vm=java, trial=0, benchmark=M1} 291.42 ns; σ=6.56 ns @ 10 trials
50% Scenario{vm=java, trial=0, benchmark=M2} 70.34 ns; σ=0.15 ns @ 3 trials

benchmark    ns linear runtime
       M1 291.4 ==============================
       M2  70.3 =======

Java 9 (almost equal performance):

 0% Scenario{vm=java, trial=0, benchmark=M2} 99,15 ns; σ=8,34 ns @ 10 trials
50% Scenario{vm=java, trial=0, benchmark=M1} 103,43 ns; σ=9,01 ns @ 10 trials

benchmark    ns linear runtime
       M2  99,1 ============================
       M1 103,4 ==============================

Java 13 (standard method is 38% faster):

 0% Scenario{vm=java, trial=0, benchmark=M2} 91,64 ns; σ=5,12 ns @ 10 trials
50% Scenario{vm=java, trial=0, benchmark=M1} 57,38 ns; σ=2,51 ns @ 10 trials

benchmark   ns linear runtime
       M2 91,6 ==============================
       M1 57,4 ==================
2 of 5
44

From the source code of java.lang.String1:

public String replace(CharSequence target, CharSequence replacement) {
   return Pattern
            .compile(target.toString(), Pattern.LITERAL)
            .matcher(this )
            .replaceAll(
                    Matcher.quoteReplacement(replacement.toString()));
}

String.replace(CharSequence target, CharSequence replacement) is implemented with java.util.regex.Pattern, therefore, it is not surprising that it is slower that StringUtils.replace(String text, String searchString, String replacement)2, which is implemented with indexOf and StringBuffer.

public static String replace(String text, String searchString, String replacement) {
    return replace(text, searchString, replacement, -1);
}

public static String replace(String text, String searchString, String replacement, int max) {
    if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) {
        return text;
    }
    int start = 0;
    int end = text.indexOf(searchString, start);
    if (end == -1) {
        return text;
    }
    int replLength = searchString.length();
    int increase = replacement.length() - replLength;
    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(replacement);
        start = end + replLength;
        if (--max == 0) {
            break;
        }
        end = text.indexOf(searchString, start);
    }
    buf.append(text.substring(start));
    return buf.toString();
}

Footnote

1 The version that I links to and copied source code from is JDK 7

2 The version that I links to and copied source code from is common-lang-2.5

🌐
Stack Overflow
stackoverflow.com › questions › 54342169
java - StringUtils.replaceEach: Replace only separate words but ...
I need to use Apache's StringUtils.replaceEach() method for replacing set of strings. However, this methods also replaces substrings in the word. I know I can use replaceAll method with \b regex. B...
🌐
HowDev
how.dev › answers › what-is-stringutilsreplacechars-in-java
What is StringUtils.replaceChars in Java?
replaceChars() in StringUtils replaces all occurrences of a search character with a replacement character in a string, returning the modified text.
Top answer
1 of 1
6

String.replaceAll and StringUtils.replace (assuming Apache Commons here) are two completely different beasts. The former is using a Regular Expression as search term and performs a replacement with support of Regular Expressions as well, the latter is just looking for occurrences of the given text and replaces it by the replacement text.

With String.replaceAll you can e.g. do something like this:

System.out.println("John Smith".replaceAll("^(\S+)\s*(\S+)\*$", "$2, $1"));

which will output

Smith, John

You can't do that with StringUtils.replace.

Assuming both libraries are available and we are not passing in a regex.

String.replaceAll is always parsing the search-term as Regex and performs the replacement assuming it to be using regex-functions as well, so it simply doesn't make sense to use this method without actually using Regex.

If you just want to do a simple text-replacement you just use String.replace(CharSequence c1, CharSequence c2) that was added with Java 1.5

From the few previous posts on this topic I see there are multiple tests and benchmarks pointing to that String.replace

Some sources would be nice, where you've seen that statement. The link Nexevis provided covered Java 1.4 where above method didn't exist and - without doing some tests myself now - I have doubts that the performance between String.replace(CharSequence...) and StringUtils.replace differ a lot because StringUtils' implementation looks quite straight forward and will most likely not differ a lot from the implementation in the JVM. The existence of it is purely historical because of the lack of a similar method in Java Version before 1.5

🌐
GeeksforGeeks
geeksforgeeks.org › java › string-handling-with-apache-commons-stringutils-class-in-java
String Handling with Apache Commons' StringUtils Class in Java - GeeksforGeeks
April 28, 2025 - Is the string empty? false Is the string blank? false The trimmed string is: hello world The substring is: llo w The replaced string is: hello Java The words in the string are: hello world The joined string is: apple, banana, orange The capitalized string is: Hello world Are the strings equal? true · Note: You'll need to have the Apache Commons Lang library added to your project's classpath in order for this program to compile and run successfully. ... import org.apache.commons.lang3.StringUtils; public class StringUtilsExample { public static void main(String[] args) { String str1 = "Hello";
🌐
GitHub
github.com › jOOQ › jOOQ › issues › 8803
Improve performance of StringUtils#replace() · Issue #8803 · jOOQ/jOOQ
March 24, 2019 - By replacing the two calls of the form stringBuilder.append(string.substring(start, end)) and stringBuilder.append(string.substring(start)) with stringBuilder.append(string, start, end) it turns out that the performance of StringUtils#replace() can be increased quite a lot (for the cases when there are indeed replacements to be made).
Published   Jun 14, 2019
🌐
Medium
medium.com › javarevisited › micro-optimizations-in-java-string-replaceall-c6d0edf2ef6
Micro optimizations in Java. String.replaceAll | by Dmytro Dumanskiy | Javarevisited | Medium
September 8, 2020 - Spring, for example, uses own custom implementation for that based on own custom replace method: public static String delete(String inString, String pattern) { return StringUtils.replace(inString, pattern, ""); }
🌐
AWS
sdk.amazonaws.com › java › api › latest › software › amazon › awssdk › utils › StringUtils.html
StringUtils (AWS SDK for Java - 2.42.6)
Replaces a String with another String inside a larger String, once. A null reference passed to this method is a no-op. StringUtils.replaceOnce(null, *, *) = null StringUtils.replaceOnce("", *, *) = "" StringUtils.replaceOnce("any", null, *) = "any" StringUtils.replaceOnce("any", *, null) = ...