มีวิธีการต่างๆ ใน Java ซึ่งคุณสามารถแยกวิเคราะห์คำในสตริงสำหรับคำเฉพาะได้ เราจะมาพูดถึง 3 เรื่องนี้กัน
เมธอด contain()
มี () วิธีการของคลาสสตริงยอมรับลำดับของค่าอักขระและตรวจสอบว่ามีอยู่ในสตริงปัจจุบันหรือไม่ หากพบว่าคืนค่าเป็น true มิฉะนั้นจะคืนค่าเป็นเท็จ
ตัวอย่าง
import java.util.StringTokenizer;
import java.util.regex.Pattern;
public class ParsingForSpecificWord {
public static void main(String args[]) {
String str1 = "Hello how are you, welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
if (str1.contains(str2)){
System.out.println("Search successful");
} else {
System.out.println("Search not successful");
}
}
} ผลลัพธ์
Search successful
เมธอด indexOf()
เมธอด indexOf() ของคลาส String ยอมรับค่าสตริงและค้นหาดัชนี (เริ่มต้น) ของค่านั้นในสตริงปัจจุบันและส่งกลับค่านั้น เมธอดนี้คืนค่า -1 หากไม่พบสตริงที่ระบุในสตริงปัจจุบัน
ตัวอย่าง
public class ParsingForSpecificWord {
public static void main(String args[]) {
String str1 = "Hello how are you, welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
int index = str1.indexOf(str2);
if (index>0){
System.out.println("Search successful");
System.out.println("Index of the word is: "+index);
} else {
System.out.println("Search not successful");
}
}
} ผลลัพธ์
Search successful Index of the word is: 30
คลาส StringTokenizer
เมื่อใช้คลาส StringTokenizer คุณสามารถแบ่งสตริงออกเป็นโทเค็นที่เล็กกว่าตามตัวคั่นและข้ามผ่านได้ ตัวอย่างต่อไปนี้จะแปลงคำศัพท์ทั้งหมดในสตริงต้นทางและเปรียบเทียบแต่ละคำกับคำที่กำหนดโดยใช้ equals() วิธีการ
ตัวอย่าง
import java.util.StringTokenizer;
public class ParsingForSpecificWord {
public static void main(String args[]) {
String str1 = "Hello how are you welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
//Instantiating the StringTookenizer class
StringTokenizer tokenizer = new StringTokenizer(str1," ");
int flag = 0;
while (tokenizer.hasMoreElements()) {
String token = tokenizer.nextToken();
if (token.equals(str2)){
flag = 1;
} else {
flag = 0;
}
}
if(flag==1)
System.out.println("Search successful");
else
System.out.println("Search not successful");
}
} ผลลัพธ์
Search successful