String类是Java中最常用的类之一,它提供了许多实用的方法来处理字符串。其中一个非常有用的方法是endsWidth(),用于检查一个字符串是否以指定的后缀结尾。下面将从多个方面对endsWith()方法进行详细解析。
一、用法及语法
endsWith()方法用于检查一个字符串是否以指定的后缀结尾。它的语法如下:
public boolean endsWith(String suffix)
其中,suffix是要检查的后缀字符串,如果字符串str以suffix结尾,则返回true;否则返回false。
endsWith()方法还可以使用第二个可选的参数来限制比较的长度。语法如下:
public boolean endsWith(String suffix, int endIndex)
其中,endIndex是比较的结束下标,比较的范围是字符串str的[0, endIndex]部分。
二、实例演示
下面通过一个具体实例演示endsWith()方法的使用。
public class EndsWithDemo {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = "world";
String str3 = "ello";
String str4 = "Hello world";
//测试1:检查str1是否以str2结尾
boolean b1 = str1.endsWith(str2);
System.out.println("str1 ends with str2: " + b1);
//测试2:使用指定的下标检查str1是否以str3结尾
boolean b2 = str1.endsWith(str3, 4);
System.out.println("str1 ends with str3 before index 4: " + b2);
//测试3:检查str4是否以str2结尾(忽略大小写)
boolean b3 = str4.toLowerCase().endsWith(str2.toLowerCase());
System.out.println("str4 ends with str2 (ignore case): " + b3);
}
}
输出结果:
str1 ends with str2: true str1 ends with str3 before index 4: true str4 ends with str2 (ignore case): true
可以看到,endsWith()方法返回了预期的结果。
三、扩展应用
1. 检查文件后缀名
endsWith()方法可以方便地检查文件后缀名。下面演示一个检查文件后缀名是否为.class的例子:
public class FileDemo {
public static void main(String[] args) {
String fileName = "Test.class";
if(fileName.endsWith(".class")) {
System.out.println("This is a Java class file.");
} else {
System.out.println("This is not a Java class file.");
}
}
}
输出结果:
This is a Java class file.
2. 遍历文件夹
endsWith()方法可以与文件IO操作相结合,用于遍历特定后缀名的文件。例如,下面的代码片段遍历一个文件夹,输出所有以.jpg结尾的图片文件:
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
String folderPath = "C:\\Pictures";
File folder = new File(folderPath);
if(folder.isDirectory()) {
//遍历文件夹
File[] fileList = folder.listFiles();
for(File file : fileList) {
if(file.isFile() && file.getName().endsWith(".jpg")) {
System.out.println(file.getAbsolutePath());
}
}
}
}
}
注意,此处需要先判断文件是否是文件夹,再遍历文件夹。
3. 实现简单的模式匹配
endsWith()方法可以用作实现简单的模式匹配。例如,下面的代码片段使用endsWith()方法查找所有以”.jpg”和”.png”结尾的文件:
import java.io.File;
public class FileDemo {
public static void main(String[] args) {
String folderPath = "C:\\Pictures";
String[] extensions = {".jpg", ".png"}; //指定要查找的后缀名
File folder = new File(folderPath);
if(folder.isDirectory()) {
//遍历文件夹
File[] fileList = folder.listFiles();
for(String ext : extensions) {
for(File file : fileList) {
if(file.isFile() && file.getName().endsWith(ext)) {
System.out.println(file.getAbsolutePath());
}
}
}
}
}
}
该代码使用了嵌套的循环,以便遍历指定的后缀名数组和文件夹中的文件。
总结
endsWith()方法是Java字符串处理中的一个实用工具,可以方便地检查一个字符串是否以指定的后缀结尾。此外,它还可以与文件IO操作相结合,用于遍历指定后缀名的文件,以及实现简单的模式匹配。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/303170.html
微信扫一扫
支付宝扫一扫