Python's String Translations for Java

14 Sep, 2008 · 2 min read · #java #python

Just as I started poking my nose into Python, I came across two really interesting functions in its string module.

  1. maketrans()
  2. translate()

These two methods when used together, can be used for string transformations based on a mapping between characters.

Java’s API didn’t seem to provide any equivalent for this. So I decided to write one just for kicks.

Note: This is not a RegEx based approach for replacing parts of a String. It uses a mapping table of characters to perform the transformation.

Here is a simple Java code to achieve what maketrans() and translate() achieve together in Python.

package translator;

import java.util.HashMap;
import java.util.Map;

public class StringTranslator {
 private Map<Character, Character> translationMap;

 public StringTranslator(String from, String to) {
  translationMap = new HashMap<Character, Character>();

  if (from.length() != to.length())
   throw new IllegalArgumentException("The from and to strings must be of the same length");

  for (int i = 0; i < from.length(); i++)
   translationMap.put(from.charAt(i), to.charAt(i));
 }

 public String translate(String str) {
  StringBuilder buffer = new StringBuilder(str);

  for (int i = 0; i < buffer.length(); i++) {
   Character ch = buffer.charAt(i);
   Character replacement = translationMap.get(ch);
   if (replacement != null)
    buffer.replace(i, i + 1, "" + replacement);
  }

  return buffer.toString();
 }

 public String translate(String str, String deleteChars) {
  StringBuilder buffer = new StringBuilder(str);
  char[] deletions = deleteChars.toCharArray();
  for (char ch : deletions) {
   int index;
   if ((index = buffer.indexOf("" + ch)) != -1)
    buffer.deleteCharAt(index);
  }

  return translate(buffer.toString());
 }
}

Once the above code is in place, here are the equivalent Python and Java code to achieve the same result.

Python Code: #

"He!!0 W0r!d".translate(maketrans("!0", "lo"))

Java Code: #

new StringTranslator("!0", "lo").translate("He!!0 W0r!d");

The constructor of the StringTranslator class takes the from and to strings for mapping like maketrans() of Python. The overloaded translate() methods take the String to be transformed and optionally another String containing the characters to be deleted (like translate() of Python). The translation table need not be passed as an argument in this case as the StringTranslator instance will already hold it.

If you liked what you read, consider subscribing to the RSS feed in your favourite feed reader.