0

我需要在我的程序中比较字符串而不考虑特殊的国家字符,所以例如“C”和“Č”应该是相同的。我使用了 Collat​​or 类。对于第一种和第二种情况,它按预期工作,但在第三种和第四种情况下没有。

包装整理器;

import java.text.Collator;
import java.util.Locale;

public class Coll {

public static void main(String[] args) {
    Locale locale = new Locale("sk", "SK");
    Collator collator = Collator.getInstance(locale);
    collator.setStrength(Collator.PRIMARY);
    System.out.println(collator.compare("T", "Ť"));
    System.out.println(collator.compare("L", "Ľ"));
    System.out.println(collator.compare("C", "Č"));
    System.out.println(collator.compare("S", "Š"));
    }
}

我期望 0 0 0 0,但实际输出是 0 0 -1 -1

4

1 回答 1

0

查看java.text.Normalizer课程。我从未广泛使用过它,但它看起来可能对您的目的有用。例子:

import java.text.Normalizer;
import java.text.Normalizer.Form;

public class NewClass2 {

    public static void main(String[] args) {

        System.out.println("T".compareTo( normalizeString("Ť") ));
        System.out.println("L".compareTo( normalizeString("Ľ") ));
        System.out.println("C".compareTo( normalizeString("Č") ));
        System.out.println("S".compareTo( normalizeString("Š") ));
        System.out.println("O".compareTo( normalizeString("Ö") ));
        System.out.println("U".compareTo( normalizeString("Ü") ));
        System.out.println("A".compareTo( normalizeString("Ä") ));
        System.out.println("A".compareTo( normalizeString("Å") ));        
    }

    public static String normalizeString(String str){
        return Normalizer.normalize(str, Form.NFD).replaceAll("[^\\p{ASCII}]", "");
    }
}

阅读此博客文章以获取更多信息:normalizing-text-in-java

于 2019-01-23T17:13:54.140 回答