代码之家  ›  专栏  ›  技术社区  ›  sunone5

Java:-以邻近方式进行字符串搜索

  •  -3
  • sunone5  · 技术社区  · 8 年前

    更具体地说:-查找任何顺序的单词1和单词2,只要它们出现在彼此的一定距离内。

    String term=“癌症问题”; String text=“二战期间,医生在日本发现了许多和癌症有关的胸部问题。”; int距离=3;//距离可能不同

    1 回复  |  直到 8 年前
        1
  •  1
  •   Eritrean    8 年前

    这是一种没有正则表达式的非常天真的方法。

    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());
        }
    }