📌  相关文章
📜  Java中的Java .lang.String.startswith()

📅  最后修改于: 2022-05-13 01:55:39.290000             🧑  作者: Mango

Java中的Java .lang.String.startswith()

startwith() 方法有两种变体。本文描述了所有这些变体,如下所示:
1. String startsWith() :此方法测试字符串是否以从第一个索引开始的指定前缀开始。

Syntax
public boolean startsWith(String prefix)
Parameters
prefix: the prefix to be matched.
Return Value
It returns true if the character sequence 
represented by the argument is a prefix of the character 
sequence represented by this string; false otherwise.
// Java code to demonstrate the
// working of  startsWith()
public class Strt1 {
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");
  
        // Testing the prefix using startsWith()
        System.out.print("Check whether string starts with Welcome : ");
        System.out.println(Str.startsWith("Welcome"));
  
        // Testing the prefix using startsWith()
        System.out.print("Check whether string starts with geeks : ");
        System.out.println(Str.startsWith("geeks"));
    }
}

输出:

Check whether string starts with Welcome : true
Check whether string starts with geeks : false

2. String startsWith(String prefix, int strt_pos):这个变体有两个参数,并测试一个字符串是否以指定的前缀开始一个指定的索引。

Syntax
public boolean startsWith(String prefix, int strt_pos)
Parameters
prefix : the prefix to be matched.
strt_pos :  where to begin looking in the string.
Return Value
It returns true if the character sequence
represented by the argument is a prefix of the character
sequence represented by this string; false otherwise.

// Java code to demonstrate the
// working of  startsWith()
public class Strt2 {
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Welcome to geeksforgeeks");
  
        // Testing the prefix using startsWith()
        System.out.print("Check whether string starts with Welcome at pos 11 : ");
        System.out.println(Str.startsWith("Welcome", 11));
  
        // Testing the prefix using startsWith()
        System.out.print("Check whether string starts with geeks at pos 11 : ");
        System.out.println(Str.startsWith("geeks", 11));
    }
}

输出:

Check whether string starts with Welcome at pos 11 : false
Check whether string starts with geeks at pos 11 : true

可能的应用:此方法主要用于过滤前缀,例如。过滤从数字开始的电话号码或从特定字母开始的名称。后一种在本文中进行了解释。

// Java code to demonstrate the
// application of  startsWith()
public class Appli {
public static void main(String args[])
    {
  
        // Initialising String
        String Str = new String("Astha Tyagi");
  
        // Testing the prefix using startsWith()
        System.out.print("Check whether Astha Tyagi starts with A : ");
        System.out.println(Str.startsWith("A"));
    }
}

输出:

Check whether Astha Tyagi starts with A : true