如何在String集合中搜索3个或更多字符的匹配项

时间:2017-01-15 04:14:41

标签: java search collections

我试图创建一个可以搜索名称集合的应用程序,并返回与您搜索到的名称相近的名称。示例:搜索了jos,jose,josie和josh都在JList中返回。

这是我用作原型的代码:

public class Window {

private JPanel pan;
private String[] names1 = {"lewis","joe","jack","ryan","kane","google","brooke"};
private LinkedList<String> names;
private String[] name;
private JTextField enterbar;
private JButton btn;
private JTextField enterbar2;
private JButton btn2;

public Window(){

    enterbar = new JTextField(10);
    btn = new JButton("enter");
    enterbar2 = new JTextField(10);
    btn2 = new JButton("Add");


    names = new LinkedList<String>();
    names.add("rose");
    pan = new JPanel();
    Font f1 = new Font("ariel", 0 , 20);
    JFrame frame = new JFrame("Contact Saver");
    DefaultListModel v = new DefaultListModel();
    v.addElement(names);
    JList list = new JList(v);

    list.setVisibleRowCount(4);//sets how many elements you can see and if    there is more it adds a scroll bar
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);//makes it so you can only select one element at a time
    list.setFixedCellWidth(600);
    list.setFixedCellHeight(30);
    list.setFont(f1);

    frame.add(enterbar);
    frame.add(btn);
    frame.add(enterbar2);
    frame.add(btn2);
    pan.add(new JScrollPane(list));
    frame.add(pan);//adds a scroll bar to the list

    frame.setLayout(new FlowLayout());
    frame.setSize(700,500);     
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);

    list.addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event) {
            System.out.println("here");
        }
    });
    btn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent event) {
            v.clear();
            if(names.contains(enterbar.getText().toLowerCase()))System.out.println("here");

            for(int i =0; i < names.size();i++){
            v.addElement(names.get(i));
        }
            System.out.println(v);
        }

    });

    btn2.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            v.clear();
            names.add(enterbar2.getText());
            for(int i =0; i < names.size();i++){
                v.addElement(names.get(i));
            }
        }

    });

}

public static void main(String args[]){
    new Window();
}

}

2 个答案:

答案 0 :(得分:0)

创建Levenshtein距离公式的实现,作为遍历列表的循环,为每个公式分配一个距离值并返回最低的 n 值。

答案 1 :(得分:0)

您可以详细阅读find()方法。 Find()在给定的字符串数组中找出子字符串以供参考,请参阅示例:

 1:Pattern.compile("[a-z]");
 2:Pattern.matcher("0a1b1c3d4"); 
 3:int count = 0; 
 4:while(matcher.find())
 { 
 5:count++;
 }