Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Cyrillic letters to English latin in Java String?

Tags:

java

letters

I have string a="L1-23Миграција од VPN и промена на брзина ACTELIS Agregator alternativna 8-/208";

I would like for every my string to check if there are some Cyrillic letters in string and to convert them to English:

Output should look:

L1-23Migracija od VPN i promena na brzina ACTELIS Agregator alternativna 8-/208

Thanks!

like image 498
Veljko Avatar asked Nov 25 '22 22:11

Veljko


1 Answers

I found this method here on stackoverflow Transliteration from Cyrillic to Latin ICU4j java, it is for converting cyrillic(Russian) to latin (but you can convert it the other way around if needed). I tweaked it a bit so it's compatible for Macedonian Cyrillic(I believe that's what you need). Here it is:

public static String convertCyrilic(String message){
    char[] abcCyr =   {' ','а','б','в','г','д','ѓ','е', 'ж','з','ѕ','и','ј','к','л','љ','м','н','њ','о','п','р','с','т', 'ќ','у', 'ф','х','ц','ч','џ','ш', 'А','Б','В','Г','Д','Ѓ','Е', 'Ж','З','Ѕ','И','Ј','К','Л','Љ','М','Н','Њ','О','П','Р','С','Т', 'Ќ', 'У','Ф', 'Х','Ц','Ч','Џ','Ш','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','/','-'};
    String[] abcLat = {" ","a","b","v","g","d","]","e","zh","z","y","i","j","k","l","q","m","n","w","o","p","r","s","t","'","u","f","h", "c",";", "x","{","A","B","V","G","D","}","E","Zh","Z","Y","I","J","K","L","Q","M","N","W","O","P","R","S","T","KJ","U","F","H", "C",":", "X","{", "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","/","-"};
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < message.length(); i++) {
        for (int x = 0; x < abcCyr.length; x++ ) {
            if (message.charAt(i) == abcCyr[x]) {
                builder.append(abcLat[x]);
            }
        }
    }
    return builder.toString();
}

And then just use

String converted = convertCyrillic(a);
like image 113
Zozinski Avatar answered Dec 15 '22 00:12

Zozinski