如何仅为字符串中的大写字符删除变音符号

时间:2012-05-01 00:58:55

标签: java normalization denormalization unicode-normalization

我需要从字符串中的大写字符中删除变音符号。 示例:ÉlectroniqueCaméras=> ElectroniqueCaméras(只有É被修改,é在Caméras仍然保持原样)

我正在使用以下方法,它仅从大写字母中删除变音符号,但重构的字符串看起来像这样 - Electronique Came?ras(é丢失)。如何正确重建字符串?

public static String removeDiacriticsFromUppercaseLetters(String input)
    {
        if (input == null)
              return input;
        String normalized= Normalizer.normalize(input, Normalizer.Form.NFD);

        StringBuilder newString = new StringBuilder();
        newString.append(normalized.charAt(0));

        for (int i=1;i<normalized.length();++i)
        {
            //Check if this diacritic is for an uppercase letter, if yes, skip
            if (Character.isUpperCase(normalized= .charAt(i-1)) && Character.getType(normalized.charAt(i)) == Character.NON_SPACING_MARK){
              continue;
            }
            else{
              newString.append(normalized.charAt(i));
            }
        }
        return newString.toString();
    }

由于

1 个答案:

答案 0 :(得分:3)

请改为尝试:

public static String removeDiacriticsFromUppercaseLetters(String input) 
{ 
    if (input == null) 
        return null; 

    String normalized = Normalizer.normalize(input, Normalizer.Form.NFD); 

    StringBuilder newString = new StringBuilder(); 
    boolean checkDiacritics = false;

    for (int i = 0; i < normalized.length(); ++i) 
    { 
        char ch = normalized.charAt(i);

        if (checkDiacritics)
        {
            if (Character.getType(ch) == Character.NON_SPACING_MARK)
                continue;

            checkDiacritics = false;
        }

        if (Character.isUpperCase(ch))
            checkDiacritics = true;

        newString.append(ch); 
    } 

    //return newString.toString(); 
    return Normalizer.normalize(newString.toString(), Normalizer.Form.NFC); 
}