Domanda

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);
È stato utile?

Soluzione

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.

Altri suggerimenti

String a="23423k!(dfgd){sdf};";
    String b=a
        .replace("(d", "{d")
        .replace("d)", "d}")
        .replace("{s", "(s")
        .replace("f}", "f)")
        .replace("!", "")
        .replace("k", "")
        ;

This works, but it is not the right way to do it. Look at using String.replace() or the StringBuffer class.

I'd build a regex to match the string and capture the substrings of interest, then use string concatenation to add the proper boilerplate back in

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top