คลาส StringUtils ของแพ็คเกจ org.apache.commons.lang3 ของไลบรารี Apache ทั่วไปมีวิธีการที่ชื่อ containsIgnoreCase() .
เมธอดนี้ยอมรับค่าสตริงสองค่าที่แสดงสตริงต้นทางและสตริงการค้นหาตามลำดับ ตรวจสอบว่าสตริงต้นทางมีสตริงการค้นหาโดยไม่สนใจตัวพิมพ์ ส่งกลับค่าบูลีนซึ่งก็คือ −
-
true หากสตริงต้นทางมีสตริงการค้นหา
-
false หากสตริงต้นทางไม่มีสตริงการค้นหา
เพื่อค้นหาว่าสตริงมีสตริงย่อยเฉพาะโดยไม่คำนึงถึงกรณี -
-
เพิ่มการพึ่งพาต่อไปนี้ในไฟล์ pom.xml ของคุณ
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>
-
รับสตริงต้นทาง
-
รับสตริงการค้นหา
-
เรียกใช้เมธอด hasIgnoreCase() โดยส่งผ่านออบเจ็กต์สตริงด้านบนสองรายการเป็นพารามิเตอร์ (ในลำดับเดียวกัน)
ตัวอย่าง
สมมติว่าเรามีไฟล์ชื่อ sample.txt ในไดเร็กทอรี D โดยมีเนื้อหาดังต่อไปนี้ -
Tutorials point originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comforts of their drawing rooms. At Tutorials point we provide high quality learning-aids for free of cost.
ตัวอย่าง
ตัวอย่าง Java ต่อไปนี้จะอ่านสตริงย่อยจากผู้ใช้และตรวจสอบว่าไฟล์มีสตริงย่อยที่ระบุโดยไม่คำนึงถึงขนาดตัวพิมพ์
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 {
String input = null;
Scanner sc = new Scanner(new File(filePath));
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input);
}
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");
//Verify whether the file contains the given sub String
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.