★ wanayoo — archive 1999 http://ibm.com/java/education/international-unicode/unicode2.5.htmlNouvelle recherche | Portail wanayoo

Introduction to IBM Classes for Unicode


2.5 Fix String Comparison

The standard comparison in String (and UnicodeString in C/C++) will only do a binary comparison. For display strings, this is almost always incorrect! Wherever the ordering or equality of strings is important to the user, such as when presenting an alphabetized list, then use a Collator instead. Otherwise a German, for example, will find that you don't equate two strings that he thinks are equal.

String Comparison

Java

Old
if (string1.equals(string2)) {... 
... 
if (string1.compare(string2) < 0) {...
New 
Collator coll = Collator.getInstance(); 

if (coll.equals(string1, string2)) {... 
... 
if (coll.compare(string1, string2) < 0) {...

     

C++

Old
if (strcmp(string1,string2) == 0) {... 
... 
if (strcmp(string1,string2) < 0) {...
New
Collator coll = Collator.createInstance(err); 
if (coll.equals(string1,string2)) {... 
... 
if (coll.compare(string1,string2) < 0) {...

   

C

Old
if (strcmp(string1,string2) == 0) {... 
... 
if (strcmp(string1,string2) < 0) {...
New
Collator* coll = T_Collator_createInstance(NULL, &err); 

if (T_Collator_equals(coll, string1, string2)) {... 
... 
if (T_Collator_compare(coll, string1, string2) < 0) {...

 

Of course, if you are comparing strings in a tight loop, you should move the creation of the collator out of the loop! You can also make your collator static to avoid repeated creations.

If a string is going to be compared multiple times, then use a CollationKey instead. This preprocesses the string to handle all of the international issues, and converts it into an internal form that can be compared with a simple binary comparison. This makes multiple comparisons much faster.

There are also a number of advanced features in Collators, such as the ability to merge in additional rules at runtime or modify the rules. For example, you can make "b" sort after "c", if you really wanted, or you can have "?" sort exactly as if it were spelled out as "question-mark". You can also use collators to do correct native-language searching as well as sorting, using a CollationElementIterator.





JavaTM is a trademark of Sun Microsystems, Inc.

Microsoft is a registered trademark of Microsoft Corporation.

Other companies, products, and service names may be trademarks or service marks of others.

Copyright    Trademark



  Java Education Java Home  

IBM HomeOrderEmployment