2017-08-11 23 views
-2

我需要一个纯Java程序来搜索给定的字符串以“找到彼此靠近的字” - 需要指定每个其他距离。 更具体地说: - 发现word1和word2的任何顺序,只要它们发生在彼此的一定距离内。例如: - 在给定字符串中相互3个字内搜索“癌症”和“问题” - 如果找到则返回“true”,否则返回“false”。Java: - 以接​​近的方式搜索字符串

String term =“cancer problems”; String text =“第二次世界大战期间,医生在日本发现许多癌症相关的胸部问题。”; int distance = 3; //距离可能不同

我更喜欢纯粹的Java解决方案,而不是正则表达式解决方案。

+1

“我更喜欢纯Java解决方案,而不是正则表达式解决方案。” - 我们希望您向我们展示您迄今为止所尝试的内容,以便我们帮助您解决问题。我们没有为你解决整个任务。 – luk2302

+0

@ luk2302所有的OP都有[显示在这里](https://stackoverflow.com/questions/45598271/java-php-preg-match),我想。 –

+0

请按照 String text =“医生在第二次世界大战期间在日本发现许多与癌症有关的问题”。 正则表达式的方法1: - \\ bcancer \\ W +:{1,6} \\问题; B 正则表达式的方法2(\\ W + \\ W +): - ???? \ B(:(>癌症()|问题()|(?> \ 1 | \ 2)\ w +)\ b \ W *?){0,2} \ 1 \ 2 \ b – sunone5

回答

1

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

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

这实际上是可以接受的。可能现在我有一些很好的方法。它实际上更好。感谢@Eritrean – sunone5