當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java String startsWith()用法及代碼示例


字符串 startsWith() 方法

startsWith() 方法是一個 String 類方法,用於檢查給定的字符串是否以特定的字符序列開頭。

如果字符串以給定的字符序列開頭 – startsWith() 方法返回true, 如果字符串不以給定的字符序列開頭 –startsWith() 方法返回false

用法:

    boolean String_object.startsWith(character_sequence);

這裏,

  • String_object是我們必須檢查它是否以給定開頭的主要字符串character_sequence與否。
  • character_sequence是要檢查的字符集。

例:

    Input:
    str = "Hello world!"
    Function call:
    str.startsWith("Hello");
    Output:
    true

    Input:
    str = "IncludeHelp"
    Function call:
    str.startsWith("inc");
    Output:
    false

碼:

public class Main
{
    public static void main(String[] args) {
        String str1 = "Hello world!";
        String str2 = "IncludeHelp";
        
        System.out.println(str1.startsWith("Hello"));
        System.out.println(str1.startsWith("inc"));
        
        //checking through the conditions
        if(str1.startsWith("Hello")){
            System.out.println(str1 + " starts with Hello" );
        }
        else{
            System.out.println(str1 + " does not start with Hello" );
        }
        //note:method is case sensitive
        if(str2.startsWith("inc")){
            System.out.println(str2 + " starts with inc" );
        }
        else{
            System.out.println(str2 + " does not start with inc" );
        }        
    }
}

輸出

true
false
Hello world! starts with Hello
IncludeHelp does not start with inc


相關用法


注:本文由純淨天空篩選整理自 Java String startsWith() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。