Convert Unicode to ASCII without changing the string length (in Java)
ascii, java, string, unicode
Solution
As stated in this answer, the following code should work:
String s = "口水雞 hello Ä";
String s1 = Normalizer.normalize(s, Normalizer.Form.NFKD);
String regex = "[\\p{InCombiningDiacriticalMarks}\\p{IsLm}\\p{IsSk}]+";
String s2 = new String(s1.replaceAll(regex, "").getBytes("ascii"), "ascii");
System.out.println(s2);
System.out.println(s.length() == s2.length());
Output is
??? hello A
true
So you first remove diactrical marks, the convert to ascii. Non-ascii characters will become question marks.
Problem
What is the best way to convert a string from Unicode to ASCII without changing it's length (that is very important in my case)? Also the characters without any conversion problems must be at the same positions as in the original string. So an "Ä" must be converted to "A" and not something cryptic that has more characters. Edit: @novalis - Such symbols (for example of asian languages) should just be converted to some placeholders. I am not too interested in those words or what they mean. @MtnViewMark - I must preserve the number of all characters and the position of ASCII available characters under any circumstance. Here some more info: I have some text mining tools that can only process ASCII strings. Most of the text that should be processed is in English, but some do contain non ASCII characters. I am not interested in those words, but I must be sure that the words I am interested in (those that only contain ASCII characters) are at the same positions after the string conversion.