Home > Mobile >  Is there a Java version of translate() and maketrasns() like in python?
Is there a Java version of translate() and maketrasns() like in python?

Time:01-28

I am making a program to convert a message into a coded form of that message. I have done this with python, ut cannot find a similar method in java.

I tried similar commands, ut none worked.

CodePudding user response:

If you mean an alternative for using the maketrans() and translate() python functions, then you can achieve similar functionality in Java by using the replace() method from the String class.

String original = "abcdefg";
String replaced = original.replace('a', 'z');
System.out.println(replaced);

This would result in the output of "zbcdefg"

CodePudding user response:

You can do it like this.

System.out.println(trans("this is a test", "tis", "xy"));
System.out.println(trans("Hello", "Heo", "Joy"));

prints

xhyx yx a xexx
Jolly

This works by simply by replacing the target character specified in the source string at location index with character in the dest string at the same location. If the destination string is shorter than the source string, then the remainder function is used to correct the index by wrapping around. Then the resultant string is returned.

public static String trans(String target, String source,String dest) {
    char[] chars = target.toCharArray();
    for(int i = 0; i < target.length(); i  ) {
        int index = source.indexOf(chars[i]);
        if (index >= 0) {
            index %= dest.length();
            chars[i] = dest.charAt(index);
        }
    }
    return new String(chars);
    
}
  • Related