Reputation: 1138
I have a text box where the user can input the string with letters and numbers in Java, i.e.
String inputString="Аs87df56VСХ6ВР";
And also the user can forget to switch the language and input this string using cyrillic alphabet, because there are similar characters in cyrillic and english alphabets: ABCEHKMOPTX
My question is: how to find and replace cyrillic letters in the input string?
Upvotes: 5
Views: 4287
Reputation: 425073
Use the replaceChars()
utility method from the StringUtils
class of the Apache common-lang library.
str = StringUtils.replaceChars(str, "АВЕЅZІКМНОРСТХШѴУ", "ABESZIKMHOPCTXWVY");
I used actual Cyrillic chars in this code (so you can copy-paste it) and added a couple of moderately similar letters too.
Upvotes: 6
Reputation: 22963
I would propose to use a HashMap to keep all the mappings and then replace them like 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 = "AАBВCСEЕHНKКMМOОPРTТYУXХ";
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);
}
}
Upvotes: 1
Reputation: 71
A slow but simple solution would be to make 2 strings with only chars 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);
}
Upvotes: 0