簡體   English   中英

使用 java 將重音字符轉換為英語

[英]Convert accent characters to english using java

我有一個要求,我需要使用可用於IcelandJapan用戶的重音字符進行搜索。 我編寫的代碼適用於一些重音字符,但不是全部。 下面的例子 -

À - returns a. Correct.
 - returns a. Correct.
Ð - returns Ð. This is breaking. It should return e.
Õ - returns Õ. This is breaking. It should return o.

以下是我的代碼: -

String accentConvertStr = StringUtils.stripAccents(myKey);

也試過這個: -

byte[] b = key.getBytes("Cp1252");
System.out.println("" + new String(b, StandardCharsets.UTF_8));

請指教。

我會說它按預期工作。 StringUtils.stripAccents 的底層代碼其實如下。

String[] chars  = new String[]{"À","Â","Ð","Õ"};

for(String c : chars){
  String normalized = Normalizer.normalize(c,Normalizer.Form.NFD);
  System.out.println(normalized.replaceAll("\\p{InCombiningDiacriticalMarks}+", ""));
}

這將 output: AA Ð O

如果您閱讀https://stackoverflow.com/a/5697575/9671280答案,您會發現

Be aware that that will not remove what you might think of as “accent” marks from all characters. There are many it will not do this for, For example. you cannot convert Đ to D or ø to o that way, For that. you need to reduce code points to those that match the same primary collation strength in the Unicode Collation Table.

如果您仍想使用 StringUtil.stripAccents,則可以單獨處理。

請嘗試https://github.com/xuender/unidecode它似乎適用於您的情況。

 String normalized = Unidecode.decode(input);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM