ในการค้นหาสตริงอินพุตที่ตรงกันทั้งหมดจากรายการ โค้ด Java มีดังต่อไปนี้ −
ตัวอย่าง
import java.io.*;
import java.util.*;
public class Demo{
static String string_encoding(String str){
HashMap<Character, Integer> my_map = new HashMap<>();
String result = "";
int i = 0;
char ch;
for (int j = 0; j < str.length(); j++) {
ch = str.charAt(j);
if (!my_map.containsKey(ch))
my_map.put(ch, i++);
result += my_map.get(ch);
}
return result;
}
static void match_words( String[] my_arr, String my_pattern){
int len = my_pattern.length();
String hash_val = string_encoding(my_pattern);
for (String word : my_arr){
if (word.length() == len && string_encoding(word).equals(hash_val))
System.out.print(word + " ");
}
}
public static void main(String args[]){
String[] my_arr = { "mno", "aabb", "pqr", "xxyy", "mmnn" };
String my_pattern = "ddcc";
System.out.println("The patterns similar to ddcc in the array are :");
match_words(my_arr, my_pattern);
}
} ผลลัพธ์
The patterns similar to ddcc in the array are : aabb xxyy mmnn
คลาสชื่อ Demo มีฟังก์ชันที่เรียกว่า 'string_encoding' ฟังก์ชันนี้จะสร้าง hashmap และวนซ้ำบนสตริงเพื่อตรวจสอบว่ามีรูปแบบใดที่ตรงกับสตริงที่เป็นปัญหาหรือไม่
ฟังก์ชันอื่นที่ชื่อ 'match_words' ถูกกำหนดให้เรียกใช้ฟังก์ชัน 'string_encoding' และตรวจสอบเพื่อดูว่ามีการจับคู่ในอาร์เรย์ที่มีรูปแบบของสตริงที่ระบุเป็นข้อมูลอ้างอิงหรือไม่ หากพบคำจะถูกส่งกลับ ในฟังก์ชันหลัก อาร์เรย์สตริงถูกกำหนดพร้อมกับรูปแบบ รูปแบบนี้เรียกฟังก์ชัน 'match_words' เอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล