Java:-以邻近方式进行字符串搜索 [英] Java :- String search in proximity manner
问题描述
我需要一个纯Java程序来搜索给定的字符串以找到彼此靠近的单词-需要指定彼此的距离。
更具体地说:-只要单词1和单词2出现在彼此之间一定距离内,它们就可以以任意顺序查找。
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.
例如:-在给定字符串中的3个单词之内搜索癌症和问题-如果找到则返回 true,否则返回 false。
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 text =医生在第二次世界大战期间在日本发现许多与癌症有关的胸部问题。
int距离= 3; //距离可能会有所不同
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
我更喜欢纯Java解决方案而不是regex解决方案。
I prefer pure Java solution rather regex solution.
推荐答案
这里是没有正则表达式的一种非常幼稚的方法。
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());
}
}
这篇关于Java:-以邻近方式进行字符串搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!