首页 > 文章列表 > 使用java的String.endsWith()函数判断字符串是否以指定后缀结尾

使用java的String.endsWith()函数判断字符串是否以指定后缀结尾

java string endsWith()
394 2023-07-26

使用Java的String.endsWith()函数判断字符串是否以指定后缀结尾

在Java编程中,我们经常需要判断一个字符串是否以某个指定的后缀结尾,这时可以使用String类提供的endsWith()函数来判断。通过该函数,我们可以有效地判断一个字符串是否以指定的后缀结尾。

String类是Java中用于表示字符串的类,它提供了许多用于操作字符串的方法。其中,endsWith()函数用于判断一个字符串是否以指定的后缀结尾,它的定义如下:

public boolean endsWith(String suffix)

该函数的功能非常简单,它接受一个String类型的参数suffix,用于指定要判断的后缀字符串。如果调用该函数的字符串以suffix结尾,即满足条件,则返回true;否则,返回false。

下面是一个例子,演示了如何使用endsWith()函数判断字符串是否以指定后缀结尾:

public class EndsWithExample {
    public static void main(String[] args) {
        String str1 = "Hello World";
        String str2 = "Java Programming";

        System.out.println("str1 ends with World: " + str1.endsWith("World")); // true
        System.out.println("str1 ends with Hello: " + str1.endsWith("Hello")); // false
        System.out.println("str2 ends with Programming: " + str2.endsWith("Programming")); // true
        System.out.println("str2 ends with Java: " + str2.endsWith("Java")); // false
    }
}

在上面的例子中,我们定义了两个字符串变量str1和str2,分别为"Hello World"和"Java Programming"。然后,我们使用endsWith()函数来判断这两个字符串是否分别以指定的后缀结尾。

运行上述代码,输出结果如下:

str1 ends with World: true
str1 ends with Hello: false
str2 ends with Programming: true
str2 ends with Java: false

通过结果可以看出,str1以"World"结尾,所以调用str1.endsWith("World")返回true;而不以"Hello"结尾,所以调用str1.endsWith("Hello")返回false。同样,str2以"Programming"结尾,所以调用str2.endsWith("Programming")返回true;而不以"Java"结尾,所以调用str2.endsWith("Java")返回false。

总结起来,使用Java的String类的endsWith()函数,可以方便地判断一个字符串是否以指定的后缀结尾。这个函数在实际的编程工作中非常有用,特别是在处理文件名、URL等场景中,可以帮助我们更加高效地进行字符串处理。