Search code examples
javastringoracle-databaseequivalentsql-function

Java Equivalent of Oracle translate


Is there any equivalent string function or library in java that behaves the way oracle translate function does?

In oracle I can do this:

select translate(
 '23423k!(dfgd){sdf};',
 '(){}k!',
 '{}()'
 ) from dual;

to get this:

23423{dfgd}(sdf);

But in java, if i did this:

    String a="23423k!(dfgd){sdf};";
    String b=a
        .replace("(", "{")
        .replace(")", "}")
        .replace("{", "(")
        .replace("}", ")")
        .replace("!", "")
        .replace("k", "")
        ;
    System.out.println("ori:"+a);
    System.out.println("mod:"+b);

i get this:

ori:23423k!(dfgd){sdf}; 
mod:23423(dfgd)(sdf);

Solution

  • Apache commons-Lang library has the StringUtils.replaceChars() utility method that does exactly this.

    The java of says:

    Replaces multiple characters in a String in one go. This method can also be used to delete characters. The length of the search characters should normally equal the length of the replace characters. If the search characters is longer, then the extra search characters are deleted.