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/zh-hant/n/303170.html