Java startsWith 方法

Java startsWith 方法是 String 方法之一,用于检查字符串是否以用户指定的子字符串开头。根据结果,startsWith 方法将返回布尔值 True 或 False。

在本文中,我们将通过一个示例展示如何编写 startsWith。下面显示了此编程语言中字符串 startsWith 的语法。

Java startsWith 语法

此编程语言提供了两个不同的 startsWith 方法。以下方法将子字符串作为参数,并检查字符串是否以该子字符串开头。

public boolean startsWIth(String Prefix); // It will return boolean True or False 

//In order to use in program
String_Object.startsWIth(String Prefix)

以下 Java startsWith 方法将子字符串作为第一个参数,并将起始索引位置(Starting_index)作为第二个参数。

此方法将从 Starting_index 开始查找,并检查 Starting_index 处的字符串是否以该子字符串开头。

public boolean startsWIth(String Prefix, int Starting_Index); // It will return boolean True or False 

//In order to use in program
String_Object.startsWIth(String Prefix, int Starting_Index)
  • Starting_Index:请指定起始索引位置。如果我们指定此值,则 String.startsWith 函数将从该位置开始查找,而不是从索引位置 0 开始。

Java startsWith 示例

在此程序中,我们将使用 startsWith 字符串方法来检查字符串是否以用户指定的子字符串开头。如果将 Starting_Index 指定为负值或大于字符串长度,则该函数将返回布尔值 False。

对于布尔值 a,它将调用 public boolean startsWith (String Prefix) 方法来检查 str 是否以 Tut 开头。如果为 TRUE,Java 将返回 TRUE;否则,返回 False。

以下 startsWith 语句将检查 str1 是否以 abc 开头。如果为 TRUE,它将返回 TRUE;否则,返回 False。

下面的 d String 方法语句将调用 public boolean startsWith (String Prefix, int Starting_Index) 方法来检查 str1 的索引位置 15 是否以 abc 开头。如果为 TRUE,则该函数将返回 TRUE;否则,返回 False。

以下 Java System.out.println 语句将打印输出。

package StringFunctions;

public class StartsWithMethod {
	public static void main(String[] args) {
		String str = "Tutorials On Java Programming";
		String str1 = "abc working at abc company";
		
		boolean a = str.startsWith("Tut");
		boolean b = str.startsWith("tut");
		boolean c = str1.startsWith("abc");
		boolean d = str1.startsWith("abc", 15);

		System.out.println("Does the String str Starts with Tut? = " + a);
		System.out.println("Does the String str Starts with tut? = " + b);
		System.out.println("Does the String str1 Starts with abc? = " + c);
		System.out.println("Starting from index 15 - Does the String str1 Starts with abc? = " + d);
	}
}
Java startsWith Method 1

Java startsWith 示例

在此 Java 程序中,我们将要求用户输入任何单词。此程序将根据用户输入的字符串值显示消息。

在此 startsWith 方法示例中,前两个语句将要求用户输入任何单词。然后我们将用户输入的值赋给 str 变量。

接下来,我们使用 If Else 语句来检查用户输入的单词是否以“ja”开头。

  • 如果为 True,则将打印 System.out.println(“Hey!! Welcome to Library”); 语句。
  • 否则,将打印 System.out.println(“Goodbye to Library”); 语句。
package StringFunctions;

import java.util.Scanner;

public class StartsWithMethod2 {
	private static Scanner sc;

	public static void main(String[] args) {
		sc = new Scanner(System.in);
		
		System.out.println("Please Enter any word: ");
		String str = sc.nextLine();
		
		if (str.startsWith("ja")) {
			System.out.println("Hey!! Welcome to Library");
		}
		else {
			System.out.println("Goodbye to Library");
		}
	}
}
Please Enter any word: 
java
Hey!! Welcome to Library

让我们输入一个不同的单词。

Please Enter any word: 
sql
Goodbye to Library