문제

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);
도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top