Translating strings character by character

First of all you need a conversion table, defining the translation for every character.

Then you read the string char by char, and use the translation table to get the translation. Easy, right?

you can use something like this:

class Translator {
 HashMap<String,String> translation = new HashMap<String,String>();

 public Translator(){
  //Populate the translation table here;
 }

 public String translate(String origin){
  String destiny="";
  for(int i=0;i<origin.length();i++){
   char character = origin.charAt(i);
   destiny = destiny + translation.get(Character.toString(character));
  }
 return destiny;
 }
}

Alternatively you could use

replaceEach(String text, String[] searchList, String[] replacementList) 
           Replaces all occurrences of Strings within another String.

From org.apache.commons.lang.StringUtils .
You could populate a String[] with the latin characters (but as String), then populate another String[] with the cyrillic characters as String, and use that function.

String[] latinCharacters = [] //Populate them
String[] cyrillicCharacters = [] //Populate them

public String translate(String origin){
return replaceEach(origin,latinCharacters,cyrillicCharacters);
}

Leave a Comment