class Test {
public static void main(String args[]) {
String s1 = "état";
String s2 = "famille";
// (javadoc)
// The result of String.compareTo() is a negative integer
// if this String object lexicographically precedes the
// argument string. The result is a positive integer if
// this String object lexicographically follows the argument
// string. The result is zero if the strings are equal;
// compareTo returns 0 exactly when the equals(Object)
// method would return true.
// here we are expecting "é" < "f"
if (s1.compareTo(s2) > 0) {
// s1 lexicographically follows s2 which is not true!
System.out.println("not ok s1 > s2 ");
}
// (javadoc)
// Collator.compare() compares the source string to the target string
// according to the collation rules for this Collator.
// Returns an integer less than, equal to or greater than zero
// depending on whether the source String is less than,
// equal to or greater than the target string.
java.text.Collator frCollator =
java.text.Collator.getInstance(java.util.Locale.FRANCE);
frCollator.setStrength(java.text.Collator.CANONICAL_DECOMPOSITION);
// or frCollator.setStrength(java.text.Collator.SECONDARY);
// to be non case sensitive
if (frCollator.compare(s1, s2) < 0) {
// s2 lexicographically follows s1
System.out.println("ok s1 < s2 ");
}
}
}Equality
class Test {
public static void main(String args[]) {
String s1 = "état";
String s2 = "État";
// here we are expecting "état" == "État"
if (s1.compareTo(s2) != 0) {
System.out.println("not ok s1 != s2 ");
}
java.text.Collator frCollator =
java.text.Collator.getInstance(java.util.Locale.FRANCE);
frCollator.setStrength(java.text.Collator.SECONDARY);
if (frCollator.compare(s1, s2) == 0) {
// s2 lexicographically follows s1
System.out.println("ok s1 == s2 ");
}
}
}Written and compiled by Réal Gagnon ©1998-2005
[ home ]