คลาส StringUtils ของแพ็กเกจ org.apache.commons.lang3 ในไลบรารี Apache Commons มีเมธอด containsIgnoreCase()
เมธอดนี้รับค่าสตริงสองค่า (source string และ search string) ตรวจสอบว่า source string มี search string อยู่หรือไม่ โดยไม่สนใจตัวพิมพ์ใหญ่/เล็ก คืนค่า boolean:
- true - หาก source string มี search string
- false - หาก source string ไม่มี search string
การเพิ่ม Dependency (Maven)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
ขั้นตอนการใช้งาน
- เพิ่ม dependency ใน pom.xml
- เตรียม source String
- เตรียม search String
- เรียก
StringUtils.containsIgnoreCase(source, search)
ตัวอย่างโค้ดครบถ้วน
import java.io.File;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class ContainsIgnoreCaseExample {
public static String fileToString(String filePath) throws Exception {
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
sb.append(sc.nextLine());
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sub string to be verified: ");
String subString = sc.next();
String fileContents = fileToString("D:\\sample.txt");
boolean result = StringUtils.containsIgnoreCase(fileContents, subString);
if (result) {
System.out.println("File contains the given sub string.");
} else {
System.out.println("File doesnot contain the given sub string.");
}
}
}
ผลลัพธ์
Enter the sub string to be verified: comforts of their drawing rooms.
File contains the given sub string.
ข้อดีของ StringUtils.containsIgnoreCase()
- จัดการ null safety อัตโนมัติ (ไม่โยน NullPointerException)
- โค้ดสั้น กระชับ อ่านง่าย
- ประสิทธิภาพดีสำหรับสตริงยาว