Java endsWith 方法

Java endsWith 方法是 String 方法之一,用于检查字符串是否以用户指定的子字符串结尾。endsWith 方法将根据结果返回布尔值 True 或 False。在本文中,我们将展示如何通过示例在编程语言中编写字符串 endsWith。

下面的 Java endsWith 方法将接受子字符串作为参数,并检查字符串是否以该子字符串结尾。

public boolean endsWIth(String suffix); // It will return boolean True or False 

//In order to use in program
String_Object.endsWIth(String suffix)

如果我们指定 Suffix 为空字符串,endsWith String 函数将返回布尔值 True 作为输出。

Java endsWith 示例

在此程序中,我们将使用 endsWith 方法检查字符串是否以用户指定的子字符串结尾。

第一个语句将调用 public boolean endsWith (String suffix) 方法来检查字符串 str 是否以 ing 结尾。如果为 TRUE,则返回 TRUE;否则返回 FALSE。

以下语句将检查 str1 是否以 company 结尾。如果为 TRUE,则返回 TRUE;否则返回 FALSE。

让我们尝试为 d 输入错误的值。以下语句将调用 public boolean endsWith (String suffix) 方法来检查 str1 是否以 abc 结尾。我们都知道这是 FALSE。以下 System.out.println 语句将打印输出。

package StringFunctions;

public class EndsWithMethod {
	public static void main(String[] args) {
		String str = "Tutorials On Java Programming";
		String str1 = "We are abc working at abc company";
		
		boolean a = str.endsWith("ing");
		boolean b = str.endsWith("Programming");
		boolean c = str1.endsWith("company");
		boolean d = str1.endsWith("abc");
		
		System.out.println("Does the String str ends with ing? = " + a);
		System.out.println("Does the String str ends with Programming? = " + b);
		System.out.println("Does the String str1 ends with company? = " + c);
		System.out.println("Does the String str1 ends with abc? = " + d);
	}
}
endsWith Method 1

Java endsWith 示例

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

在此 String 方法示例中,第一个语句将要求用户输入任何单词。然后我们将用户输入的值赋给字符串变量 str。

接下来,我们使用 If Else 语句来检查用户输入的字符串是否以“java”结尾。

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

import java.util.Scanner;

public class EndsWithMethod2 {
	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.endsWith("java")) {
			System.out.println("Hey!! Welcome to Tutorials");
		}
		else {
			System.out.println("Goodbye to Programming");
		}
	}
}
Please Enter any word: 
hello java
Hey!! Welcome to Tutorials

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

Please Enter any word: 
hi friends
Goodbye to Programming