Java 程式檢查字串結尾


通常,endswith() 方法Java 中用於檢查給定字串是否以特定字尾字串結尾。如果子字串以特定字串結尾,則它將返回布林值 true,否則如果未找到該值,則返回 false。

語法
public boolean endsWith(String suffix)

問題陳述

編寫一個程式,檢查字串是否以 Java 中的特定子字串結尾 -

輸入

str = demo

輸出

The string ends with the word mo

檢查字串結尾的步驟

以下是檢查特定子字串的步驟 -

  • 開始
  • 建立一個字串。
  • 使用endsWith() 方法檢視字串是否以所需的子字串結尾。
  • 實現一個if-else 條件語句,根據結果列印相應的訊息。
  • 停止

Java 程式檢查字串結尾

以下是檢查字串結尾的 Java 程式 -

public class Demo {
    public static void main(String[] args) {
       String str = "demo";
       if(str.endsWith("mo")) {
          System.out.println("The string ends with the word mo");
       } else {
          System.out.println("The string does not end with the word mo");
       }
    }
}

輸出

The string ends with the word mo

程式碼解釋

假設以下為我們的字串 -

String str = "demo";

現在,使用endsWith() 方法在 if-else 條件中檢查子字串“mo”。

if(str.endsWith("mo")) {
 System.out.println("The string ends with the word mo");
} else {
 System.out.println("The string does not end with the word mo");
}

在這篇文章中,我們學習瞭如何在 Java 中使用endsWith() 方法來檢查字串結尾。

更新於: 2024年8月2日

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告