Java :- String search in proximity manner

。_饼干妹妹 提交于 2019-12-13 09:38:20

问题


I need a pure Java program to search on a given string to "find words near each other" - each-other distance need to be specified. More specifically said :- finds word1 and word2 in any order, as long as they occur within a certain distance of each other.

For example :- to search for a "cancer" and "problems" within 3 words of each other in a given string - if found return "true" else return "false".

String term = "cancer problems"; String text = "doctors found many cancer related chest problems in japan during second world war."; int distance = 3; // distance may vary

I prefer pure Java solution rather regex solution.


回答1:


Here is a very naive way without regex.

public class NotElegant {

    public static void main(String[] args){
        String text = "doctors found many cancer related chest problems in japan during second world war.";
        String term = "cancer problems";
        System.out.println(getWordsNearEachOther(text,term,3));
    }
    public static String getWordsNearEachOther(String text, String term, int distance){
        String word1= term.split(" ")[0];
        String word2= term.split(" ")[1];
        String firstWord = text.indexOf(word1)<text.indexOf(word2)?word1:word2;
        String secondWord = text.indexOf(word1)<text.indexOf(word2)?word2:word1;
        if(!(text.contains(word1) && text.contains(word2))){
            return null;
        }        
        else if(text.substring(text.indexOf(firstWord), text.indexOf(secondWord)+secondWord.length()).split(" ").length>distance+1){
            return null;
        }
        return text.substring(text.indexOf(firstWord), text.indexOf(secondWord)+secondWord.length());
    }
}


来源:https://stackoverflow.com/questions/45631391/java-string-search-in-proximity-manner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!