欢迎访问宙启技术站
智能推送

Java函数:如何判断一个字符串是否以指定的后缀结尾?

发布时间:2023-07-06 08:02:45

在Java中,我们可以使用String类的endsWith()方法来判断一个字符串是否以指定的后缀结尾。该方法的语法如下:

public boolean endsWith(String suffix)

该方法接受一个字符串suffix作为参数,它是我们要判断的后缀。endsWith()方法会返回一个boolean值,如果字符串以指定的后缀结尾,则返回true;否则返回false。

以下是一个示例代码,演示了如何使用endsWith()方法来判断一个字符串是否以指定的后缀结尾:

public class Main {
    public static void main(String[] args) {
        String str1 = "Hello World";
        String str2 = "Hello";
        String suffix = "World";
        
        // 使用endsWith()方法判断字符串是否以指定的后缀结尾
        boolean endsWithSuffix1 = str1.endsWith(suffix);
        boolean endsWithSuffix2 = str2.endsWith(suffix);
        
        System.out.println("str1 ends with " + suffix + ": " + endsWithSuffix1);
        System.out.println("str2 ends with " + suffix + ": " + endsWithSuffix2);
    }
}

上述代码输出结果为:

str1 ends with World: true
str2 ends with World: false

在示例代码中,我们创建了两个字符串str1和str2,以及一个后缀suffix。使用endsWith()方法来判断str1和str2是否以suffix结尾,结果分别保存在endsWithSuffix1和endsWithSuffix2中。最后,通过System.out.println()来打印结果。

需要注意的是,endsWith()方法是区分大小写的。如果需要不区分大小写,可以使用toLowerCase()方法将字符串转换为小写,然后再使用endsWith()方法进行判断。例如:

String str = "Hello World";
String suffix = "world";
boolean endsWithSuffix = str.toLowerCase().endsWith(suffix.toLowerCase());

这样就可以忽略后缀的大小写进行判断了。

总结:使用Java的String类的endsWith()方法可以判断一个字符串是否以指定的后缀结尾,它返回一个boolean值,true表示以指定的后缀结尾,false表示不是以指定的后缀结尾。