开发者

How can I get the same result of the "tr///" operator from perl in java

What is the fastest way to implement the perl operator tr///?

For instance, if I were to have a String "ATGCA开发者_JS百科TGC" and I use perl tr/GTCA/CAGT/ then I would get "TACGTACG".

Is there a single java function that does this?


There's no way to do it using standard java. There is however the apache commons-lang library method StringUtils.replaceChars(String str, String searchChars, String replaceChars)

Use in like this:

import org.apache.commons.lang.StringUtils;

StringUtils.replaceChars("ATGCATGC", "GTCA", "CAGT"); // "TACGTACG"

Good luck with your genetics research :)


As others have commented, Apache Commons StringUtils will do it for you. So will this method, though:

    public static String replaceChars(final String str, final String sourceChars, final String replaceChars) {

    int ix;
    final StringBuilder sb = new StringBuilder(str);
    for (int i = 0 ; i < sb.length() ; i++) {
        if ((ix = sourceChars.indexOf(sb.charAt(i))) != -1) {
            sb.replace(i, i + 1, replaceChars.substring(ix, ix + 1));
        }
    }

    return sb.toString();
}


You start with

perldoc -f tr

which says:

The transliteration operator...

Now that you know a good search term, enter:

java transliteration

into the little box at google.com.

This first hit looks interesting:

jtr, a transliteration library for Java
jtr.sourceforge.net
jtr is a small Java library that emulates the 
Perl 5 "transliterate" operation on a given string. 
Most Perl 5 features are supported, including all the standard ...


There is no built-in function to do this in Java. A really basic function to just replace every occurence of one char with another would be:

public static String transliterate(String str, String source, String target) {
    StringBuilder builder = new StringBuilder();
    for(int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        int j = -1;
        for(int k = 0; k < source.length(); k++) {
            if(source.charAt(k) == ch) {
                j = k;
                break;
            }
        }
        if(j > -1 && j < target.length()) {
            builder.append(target.charAt(j));
        } else {
            builder.append(ch);
        }
    }
    return builder.toString();
}

public static void main(String[] args) {
     System.out.println(transliterate("ABCDDCBDA", "ABCD", "1234"));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜