java 指定した文字列が先頭に含まれているかを判定する

java 指定した文字列が先頭に含まれているかを判定する

javaで、指定した文字列が先頭に含まれているかを判定する手順を記述してます。「startsWith」二文字列を指定することで可能です。

環境

  • OS windows11 home
  • java 19.0.1

手順

指定した文字列が先頭に含まれているかを判定するには、「startsWith」で可能です。

対象の文字列.startsWith( "文字列" )

※含まれていれば「true」,含まれていなければ「false」

実際に、使用してみます。

public class App {
    public static void main(String[] args) throws Exception {

        String str = "mebee";        
        
        System.out.println(str.startsWith("m")); // true       
        System.out.println(str.startsWith("me")); // true
        System.out.println(str.startsWith("eb")); // false
        System.out.println(str.startsWith("M")); // false

    }
}

判定されていることが確認できます。

後方から確認

逆に、後方から確認する場合は「endsWith」を使用します。

public class App {
    public static void main(String[] args) throws Exception {

        String str = "mebee";        
        
        System.out.println(str.endsWith("e")); // true       
        System.out.println(str.endsWith("ee")); // true
        System.out.println(str.endsWith("me")); // false
        System.out.println(str.endsWith("E")); // false

    }
}