Java. Ignore accents when comparing strings

Solution 1:

I think you should be using the Collator class. It allows you to set a strength and locale and it will compare characters appropriately.

From the Java 1.6 API:

You can set a Collator's strength property to determine the level of difference considered significant in comparisons. Four strengths are provided: PRIMARY, SECONDARY, TERTIARY, and IDENTICAL. The exact assignment of strengths to language features is locale dependant. For example, in Czech, "e" and "f" are considered primary differences, while "e" and "ě" are secondary differences, "e" and "E" are tertiary differences and "e" and "e" are identical.

I think the important point here (which people are trying to make) is that "Joao"and "João" should never be considered as equal, but if you are doing sorting you don't want them to be compared based on their ASCII value because then you would have something like Joao, John, João, which is not good. Using the collator class definitely handles this correctly.

Solution 2:

You didn't hear this from me (because I disagree with the premise of the question), but, you can use java.text.Normalizer, and normalize with NFD: this splits off the accent from the letter it's attached to. You can then filter off the accent characters and compare.

Solution 3:

Or use stripAccents from apache StringUtils library if you want to compare/sort ignoring accents :

 public int compareStripAccent(String a, String b) {
    return StringUtils.stripAccents(a).compareTo(StringUtils.stripAccents(b));
}

Solution 4:

Java's Collator returns 0 for both "a" and "á", if you configure it to ignore diacritics:

public boolean isSame(String a, String b) {
    Collator insenstiveStringComparator = Collator.getInstance();
    insenstiveStringComparator.setStrength(Collator.PRIMARY);
    return insenstiveStringComparator.compare(a, b) == 0;
}

isSame("a", "á") yields true