如何在 Java 中查詢字串中的一個單詞



問題描述

如何查詢字串中的一個單詞?

解決方案

此示例展示瞭如何使用 indexOf() 方法查詢字串物件中的一個單詞,如果找到該單詞,該方法將返回該單詞在字串中的位置索引。否則,它將返回 -1。

public class SearchStringEmp{
   public static void main(String[] args) {
      String strOrig = "Hello readers";
      int intIndex = strOrig.indexOf("Hello");
      
      if(intIndex == - 1) {
         System.out.println("Hello not found");
      } else {
         System.out.println("Found Hello at index " + intIndex);
      }
   }
}

結果

以上程式碼示例將生成以下結果。

Found Hello at index 0

此示例展示瞭如何查詢字串物件中的一個單詞

public class HelloWorld {
   public static void main(String[] args) {
      String text = "The cat is on the table";
      System.out.print(text.contains("the"));
   }
}

結果

以上程式碼示例將生成以下結果。

true
java_strings.htm
廣告
© . All rights reserved.