如何檢查字串是否以特定子字串開頭 Java?


String 類可以用於表示字元字串,Java 程式中的所有字串文字都作為 String 類的例項實現。字串是常量,一旦建立,就不能更改它們的值(不可變)。

我們可以使用 String 類的 startsWith() 方法來檢查一個字串是否以一個特定的字串開頭,它會返回一個布林值,真或假。

語法

public boolean startsWith(String prefix)

示例

public class StringStartsWithSubStringTest {
   public static void main(String[] args) {
      String str = "WelcomeToTutorialsPoint";
      if(str.startsWith("Welcome")) {
         System.out.println("Begins with the specified word!");
      }
      else {
         System.out.println("Does not begin with the specified word!");
      }
   }
}

輸出

Begins with the specified word!

更新於: 2023 年 12 月 1 日

1K+ 瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.