コツコツ学習ブログ

プログラマのweb上のメモ的なもの

Javaで2つの文字列を辞書順で比較

Atcoderでたまに出てくる辞書順問題。 基本的に、インタフェースComparableを実装した Stringクラスのcompareto()を使用する。

戻り値は結果に応じて-1,0,1 のいずれかが返却される

     String textA = "aa";
        String textB = "bbb";
    int compare = textA.compareTo(textB);
        if(compare < 0) {
            System.out.println(textA);
        }else {
            System.out.println(textB);
        }

"aa"が出力される