0

I read that using String.replaceAll is very slow. This how I do in old way:

String settence = "Java /*with*/ lambda /*expressions*/";
String replaceSettence = settence.replaceAll(Pattern.quote("/*with*/"), "is").replaceAll(Pattern.quote("/*expressions*/"), "future");

System.out.println(replaceSettence);

How can I do this with StringUtils in one line?

EDIT:

Thanks for the quick answers.

I use code provided by Steph. My conclusion is that replaceAll is must faster that StringUtils:

  Long startTime = System.currentTimeMillis();
        String settence = "Java /*with*/ lambda /*expressions*/";
        String replaceSettence = settence.replaceAll(Pattern.quote("/*with*/"), "is").replaceAll(Pattern.quote("/*expressions*/"), "future");

        System.out.println(replaceSettence + " " + (System.currentTimeMillis() - startTime));

        String settenceStringUtils = "Java /*with*/ lambda /*expressions*/";
        String replaceStringUtils = StringUtils.replaceEach(settence, new String[]{"/*with*/", "/*expressions*/"}, new String[]{"is", "future"});
        System.out.println(replaceStringUtils + "StringUtils-> " + (System.currentTimeMillis() - startTime));
Goldbones
  • 1,407
  • 3
  • 21
  • 55

1 Answers1

3

Just like this:

String settence = "Java /*with*/ lambda /*expressions*/";
String replaceSettence = StringUtils.replaceEach(settence, new String[]{"/*with*/", "/*expressions*/"}, new String[]{"is","future"});
System.out.println(replaceSettence);
Steph
  • 779
  • 1
  • 8
  • 18
  • Is there any way to replace word Eg. text: "Princeton Group, Pa" => key:"inc", value:"" this will replace a substring and not a word – Syed Rafi Sep 01 '20 at 13:44
  • Yes, you can use space in regex to catch words. Or split your sentence by space and you will have an array of words so you are able to replace what you want. – Steph Sep 03 '20 at 07:10