如何在 Java 中搜索字符串内的单词

要在 Java 中搜索字符串内的单词,我们可以使用不同的方法。以下是在字符串内搜索单词的方法 -

  • 使用 indexOf() 方法

  • 使用 contains() 方法

使用 indexOf() 方法

indexOf() 方法 返回一个数值,表示字符串内匹配的子字符串的第一个字符的索引。如果未找到子字符串,则返回 -1。该方法也区分大小写,可用于搜索字符串中的单个字符或一组字符(子字符串)。

示例

此示例展示了如何使用 indexOf() 方法在 String 对象中搜索单词,如果找到该单词,则返回该单词在字符串中的位置索引。否则返回 -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

使用 contains() 方法

contains() 方法 检查字符串是否包含特定字符序列。如果在字符串中找到该序列,则返回 true,否则返回 false。此方法区分大小写,通常用于验证子字符串是否存在于较大的字符串中。

示例

以下示例展示了如何在 String 对象中搜索单词

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.html