Java如何检查以特定单词结尾的字符串?

该String.endsWith()方法可用于检查字符串是否以特定单词结尾。true如果在字符串对象的末尾找到后缀,它将返回一个布尔值。

在此示例中,我们将通过创建一个名为的类来开始代码StringEndsWithExample。此类具有main()使该类可执行的标准方法。在该main()方法中,我们创建一个名为的字符串变量,str并为其分配文本。

在下面的行中,您可以看到一个if条件语句来检查该str字符串以结尾"lazy dog"。如果以该单词结尾,则将执行if语句中的相应块。

package org.nhooo.example.lang;

public class StringEndsWithExample {
    public static void main(String[] args) {
        String str = "The quick brown fox jumps over the lazy dog";

        // 好吧,狐狸会跳过一条懒狗吗?
        if (str.endsWith("lazy dog")) {
            System.out.println("The dog is a lazy dog");
        } else {
            System.out.println("Good dog!");
        }

        // 以空字符串结尾。
        if (str.endsWith("")) {
            System.out.println("true");
        }

        // 以相同的字符串结尾。
        if (str.endsWith(str)) {
            System.out.println("true");
        }
    }
}

您需要知道的另一件事是,endsWith()如果您传入一个空字符串或与该字符串相等的另一个字符串作为参数,则该方法将返回true。此方法也区分大小写。

当您运行上面的代码片段时,您会看到打印出以下行:

The dog is a lazy dog
true
true