Java如何检查字符串是否包含特定单词?

在此代码示例中,我们将学习如何在字符串中查找特定的单词或文本。对于此示例,我们将利用java.lang.String该类。的String类提供一个调用的方法String.indexOf()。它带有一个参数a String,这是我们想要在另一个字符串中找到的子字符串。您可以将子字符串想象为我们将在大海捞针中找到的针。

如果单词在字符串中多次发现,则该indexOf()方法返回在指定字符串中找到的子字符串的第一个索引。如果找不到子字符串,则此方法返回-1。此方法返回的字符串索引从零开始。这意味着字符串中的第一个字母具有索引号0。

我们可以使用的另一种方法是String.contains()方法。此方法在JDK 1.5中引入。该方法简单地返回一个布尔值,它是true或false表示在草堆在搜索的字符串是否被找到。让我们看看下面的代码片段:

package org.nhooo.example.lang;

public class StringContainsExample {
    public static void main(String[] args) {
        String haystack = "Nhooo - Learn Java by Examples";

        // 检查是否在干草堆中找到单词“ Java”"Java" is found in the haystack
        // 变量。
        String needle = "Java";
        if (haystack.indexOf(needle) != -1) {
            System.out.println("Found the word " + needle +
                    " at index number " + haystack.indexOf(needle));
        } else {
            System.out.println("Can't find " + needle);
        }

        // 或者,如果您不感兴趣,请使用String.contains()方法
        // 与单词的索引。
        if (haystack.contains(needle)) {
            System.out.println("Eureka we've found Java!");
        }
    }
}

运行示例可以得到以下结果:

Found the word Java at index number 17
Eureka we've found Java!