Julio Diaz
Julio Diaz

Reputation: 9437

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 "ATGCATGC" and I use perl tr/GTCA/CAGT/ then I would get "TACGTACG".

Is there a single java function that does this?

Upvotes: 2

Views: 707

Answers (4)

RichW
RichW

Reputation: 2024

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();
}

Upvotes: 1

David McLaughlin
David McLaughlin

Reputation: 5188

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"));
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425208

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 :)

Upvotes: 2

tadmc
tadmc

Reputation: 3744

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 ...

Upvotes: 0

Related Questions