目录

如何在字符串中搜索单词?(How to search a word inside a string?)

问题描述 (Problem Description)

如何在字符串中搜索单词?

解决方案 (Solution)

此示例显示了如何使用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);
      }
   }
}

结果 (Result)

上面的代码示例将产生以下结果。

Found Hello at index 0

此示例显示了我们如何在String对象中搜索单词

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

结果 (Result)

上面的代码示例将产生以下结果。

true
↑回到顶部↑
WIKI教程 @2018