用 Java 在字串中查詢字元和子字串


以下 Java 程式用於在字串中搜索字元和子字串 −

示例

 即時演示

import java.io.*;
import java.lang.*;
public class Demo {
   public static void main (String[] args) {
      String test_str = "Hello";
      CharSequence seq = "He";
      boolean bool_1 = test_str.contains(seq);
      System.out.println("Was the substring found? " + bool_1);
      boolean bool_2 = test_str.contains("Lo");
      System.out.println("Was the substring found? " + bool_2);
   }
}

輸出

Was the substring found? true
Was the substring found? False

Demo 類中包含 main 函式。在此,定義字串並建立 CharSequence 例項。使用與字串關聯的 ‘contains’ 函式檢查原始字串中是否包含特定的子字串。然後將其列印在螢幕上。

更新於: 2020-09-14

588 次瀏覽

為您的 事業助力

透過完成課程取得認證

開始學習
Advertisement