Collator
文字列の比較方法を制御できないため、Javadocを読んだ後は使用しません。ロケールを選択することはできますが、そのロケールがCollator
文字列を比較する方法をどのように指示するかはあなたの手に負えません。
文字列内の文字がすべてASCII文字であることがわかっている場合はString.compareTo()
、Unicode文字値に基づいて辞書式順序でソートするメソッドを使用します。文字列内のすべての文字がASCII文字である場合、それらのUnicode文字値はそれらのASCII値になるため、それらのUnicode値で辞書式順序で並べ替えるのは、ASCII値で辞書式順序で並べ替えるのと同じになりますg_ascii_stcasecmp
。また、大文字と小文字を区別しない必要がある場合は、を使用できますString.compareToIgnoreCase()
。
コメントで述べたように、独自の比較関数を作成する必要があると思います。ASCII範囲にない文字をスキップして、文字列内の文字をループする必要があります。したがって、このようなものは、単純で愚かな実装であり、私が想像するコーナーケースをカバーするために強化する必要がありますg_ascii_strcasecmp
。
public int compareStrings(String str) {
List<Character> myAsciiChars = onlyAsciiChars(this.wordString);
List<Character> theirAsciiChars = onlyAsciiChars(str);
if (myAsciiChars.size() > theirAsciiChars.size()) {
return 1;
}
else if (myAsciiChars.size() < theirAsciiChars.size()) {
return -1;
}
for (int i=0; i < myAsciiChars.size(); i++) {
if (myAsciiChars.get(i) > theirAsciiChars.get(i)) {
return 1;
}
else if (myAsciiChars.get(i) < theirAsciiChars.get(i)) {
return -1;
}
}
return 0;
}
private final static char MAX_ASCII_VALUE = 127; // (Or 255 if using extended ASCII)
private List<Character> onlyAsciiChars(String s) {
List<Character> asciiChars = new ArrayList<>();
for (char c : s.toCharArray()) {
if (c <= MAX_ASCII_VALUE) {
asciiChars.add(c);
}
}
return asciiChars;
}