当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。