Java文字列compareTo()メソッド
例
2つの文字列を比較します。
String myStr1 = "Hello";
String myStr2 = "Hello";
System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal
定義と使用法
このcompareTo()
メソッドは、2つの文字列を辞書式に比較します。
比較は、文字列内の各文字のUnicode値に基づいています。
文字列が他の文字列と等しい場合、メソッドは0を返します。文字列が他の文字列よりも小さい(文字数が少ない)場合は0未満の値が返され、文字列が他の文字列よりも大きい(文字数が多い)場合は0より大きい値が返されます。
ヒント: compareToIgnoreCase()を使用して、小文字と大文字の違いを無視して、2つの文字列を字句的に比較します。
ヒント:equals()メソッドを使用して、Unicode値を考慮せずに2つの文字列を比較します。
構文
public int compareTo(String string2)
public int compareTo(Object object)
パラメータ値
Parameter | Description |
---|---|
string2 | A String , representing the other string to be compared |
object | An Object , representing an object to be compared |
技術的な詳細
戻り値: | 値:文字列が他のint 文字列と等しい場合は0。文字列が辞書式に他の文字列よりも小さい場合は<0 >文字列が辞書式に他の文字列よりも大きい(より多くの文字)場合は0 |
---|
❮文字列メソッド