How to replace similar Cyrillic and English characters
I have a textbox where the user can enter a string with letters and numbers in Java, i.e.
String inputString = "s87df56V6";
And also the user may forget to switch the language and enter this string using the Cyrillic alphabet, because there are similar characters in the Cyrillic and English alphabets: ABCEHKMOPTX
My question is how to find and replace cyrillic letters in the input string?
source to share
Use the utility replaceChars()
from StringUtils
the Apache common-lang library.
str = StringUtils.replaceChars(str, "ЅZІѴ", "ABESZIKMHOPCTXWVY");
I used real Cyrillic characters in this code (so you can copy it) and added a couple of moderately similar letters.
source to share
A slow but simple solution would be to make 2 lines with the only characters you want to replace:
String yourtext = " this is a sample text";
String cyrillic = "ABHOP..."
String latin = "ABNOP..."
for(int i = 0;i<yourtext.length();i++){
for(int j = 0;j<latin.length();j++){
if( latin.charAt(j) == yourtext.charAt(i)){
yourtext = changeCharInPoistion(i,cyrillic.charAt(j), yourtext);
}
}
}
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
source to share
I would suggest using a HashMap to keep all mappings and then replace them as shown in the snippet
HashMap<Character, String> mapping = new HashMap<>();
mapping.put('\u0410', "A");
mapping.put('\u0412', "B");
mapping.put('\u0421', "C");
mapping.put('\u0415', "E");
mapping.put('\u041D', "H");
mapping.put('\u041A', "K");
mapping.put('\u041C', "M");
mapping.put('\u041E', "O");
mapping.put('\u0420', "P");
mapping.put('\u0422', "T");
mapping.put('\u0423', "Y");
mapping.put('\u0425', "X");
// String contains latin+cyrillic characters
String input = "ABCEHKMOPTYX";
StringBuilder sb = new StringBuilder(input.length());
for (Character c : input.toCharArray()) {
if (c > 'Z') {
System.out.printf("add latin: %s for cyrillic: %s%n", mapping.get(c), c);
sb.append(mapping.get(c));
} else {
System.out.printf("add latin: %s%n", c);
sb.append(c);
}
}
source to share