เมธอด contains() ของคลาส String ตรวจสอบ substring แบบ case-sensitive เมธอด toLowerCase() แปลงสตริงเป็นตัวพิมพ์เล็กทั้งหมด
วิธีการ: แปลงทั้งคู่เป็นตัวพิมพ์เล็กก่อนเปรียบเทียบ
- รับ source String
- รับ sub String
- แปลง source String เป็น lowercase เก็บในตัวแปร fileContents
- แปลง sub String เป็น lowercase เก็บในตัวแปร subString
- เรียก
fileContents.contains(subString)
ตัวอย่างโค้ดครบถ้วน
import java.io.File;
import java.util.Scanner;
public class SubStringExample {
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");
// แปลงทั้งคู่เป็น lowercase
fileContents = fileContents.toLowerCase();
subString = subString.toLowerCase();
boolean result = fileContents.contains(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.
วิธีทางเลือก: ใช้ RegionMatches
เมธอด regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) สามารถเปรียบเทียบ substring โดยไม่สนใจ case ได้โดยไม่ต้องสร้างสตริงใหม่:
String source = "Hello World";
String search = "world";
boolean found = false;
for (int i = 0; i <= source.length() - search.length(); i++) {
if (source.regionMatches(true, i, search, 0, search.length())) {
found = true;
break;
}
}
ข้อควรระวัง
toLowerCase()สร้างออบเจ็กต์ String ใหม่ ใช้หน่วยความจำน้อยเพิ่ม- สำหรับ Unicode/ภาษาอื่น อาจควรใช้
toLowerCase(Locale.ROOT)เพื่อความถูกต้อง - Java 11+ สามารถใช้
String.contains()ร่วมกับString.toLowerCase()ได้สะดวกกว่า