Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

java - How to compare non english characters with accents

I want to compare 2 strings which have some non English character in them

String1 = debarquer
String2 = débárquér

On comparing above 2 strings, they should say equal.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the Collator class. It allows you to set a strength and locale and it will compare characters appropriately.

It should be something similar to this (NOTE: I have not tested the program)

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

public class CollatorExp {

    public static void main(String[] args) {
        Collator collator = Collator.getInstance(Locale.FRENCH);
        collator.setStrength(Collator.PRIMARY);

        if (collator.compare("débárquér", "debarquer") == 0) {
            System.out.println("Both Strings are equal");
        } else {
            System.out.println("Both Strings are not equal");
        }
    } 
}

UPDATE: A point to note is that "débárquér" and "debarquer" should never be considered as equal. But if you will be sorting them out, then you do not want them to be compared based on their ASCII value. Take for example "Joao" and "Jo?o": If you sort them out based on ASCII, you might get Joao, John, Jo?o. This is obviously not good. Using the collator class handles this correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...