Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีค้นหาคำเฉพาะในสตริงด้วย Java

มีหลายวิธีใน Java สำหรับค้นหาคำเฉพาะในสตริง นี่คือ 3 วิธีหลัก:

1. เมธอด contains()

เมธอด contains() ตรวจสอบว่าลำดับตัวอักษรที่กำหนดมีอยู่ในสตริงหรือไม่ คืนค่า true หากพบ false หากไม่พบ

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

2. เมธอด indexOf()

เมธอด indexOf() หา index เริ่มต้นของสตริงย่อย คืนค่า -1 หากไม่พบ

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

3. คลาส StringTokenizer

แบ่งสตริงเป็น tokens ตาม delimiter แล้วเปรียบเทียบแต่ละ token

import java.util.StringTokenizer;
String str1 = "Hello how are you welcome to Tutorialspoint";
String str2 = "Tutorialspoint";
StringTokenizer tokenizer = new StringTokenizer(str1, " ");
int flag = 0;
while (tokenizer.hasMoreElements()) {
    String token = tokenizer.nextToken();
    if (token.equals(str2)) { flag = 1; }
}
System.out.println(flag == 1 ? "Search successful" : "Search not successful");

ผลลัพธ์: Search successful

ตัวเลือกเพิ่มเติม: Regular Expression

สำหรับการค้นหาที่ซับซ้อนกว่า สามารถใช้ Pattern และ Matcher ได้:

Pattern pattern = Pattern.compile("\\bTutorialspoint\\b");
Matcher matcher = pattern.matcher(str1);
if (matcher.find()) { System.out.println("Found"); }

สรุปการเลือกใช้

  • contains() - เรียบง่าย ใช้ตรวจสอบการมีอยู่เท่านั้น
  • indexOf() - ต้องการทราบตำแหน่ง
  • StringTokenizer - ต้องการแยกคำตาม delimiter
  • Regex - รูปแบบการค้นหาซับซ้อน (word boundary, case-insensitive, ฯลฯ)