ประกอบด้วย() เมธอดของคลาส String ยอมรับค่า Sting เป็นพารามิเตอร์ ตรวจสอบว่าอ็อบเจ็กต์ String ปัจจุบันมี String ที่ระบุหรือไม่ และคืนค่า จริง หากมี (อย่างอื่นเป็นเท็จ)
toLoweCase() วิธีการของคลาส String แปลงอักขระทั้งหมดใน String ปัจจุบันเป็นตัวพิมพ์เล็กและส่งคืน
เพื่อค้นหาว่าสตริงมีสตริงย่อยเฉพาะโดยไม่คำนึงถึงกรณี -
-
รับสตริง
-
รับสตริงย่อย
-
แปลงค่าสตริงเป็นตัวพิมพ์เล็กโดยใช้เมธอด toLowerCase() จัดเก็บเป็น fileContents
-
แปลงค่าสตริงเป็นตัวพิมพ์เล็กโดยใช้เมธอด toLowerCase() เก็บเป็นสตริงย่อย
-
เรียกใช้ contains() เมธอดบน fileContents โดยส่ง subString เป็นพารามิเตอร์ไป
ตัวอย่าง
สมมติว่าเรามีไฟล์ชื่อ 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;
public class SubStringExample {
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");
//Converting the contents of the file to lower case
fileContents = fileContents.toLowerCase();
//Converting the sub string to lower case
subString = subString.toLowerCase();
//Verify whether the file contains the given sub String
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.