2017-08-11 8 views
-2

"互いに近い単語を見つける"ために、指定された文字列を検索するには純粋なJavaプログラムが必要です - それぞれの距離を指定する必要があります。 より具体的には次のように言います。 - word1とword2を互いにある距離内にある限り、任意の順序で検索します。Java: - 近接検索による文字列検索

たとえば: - 指定された文字列内で互いに3語以内の "癌"と "問題"を検索する - 見つかった場合は "true"を返し、そうでなければ "false"を返します。

文字列term = "cancer problems"; 文字列= "第二次世界大戦中に医師が日本で多数の癌関連胸の問題を発見しました。 int距離= 3; //距離が変わる可能性があります

私は純粋なJavaソリューションではなく、正規表現ソリューションです。

+1

"純粋なJavaソリューションではなく、正規表現ソリューションです。" - 私たちはあなたがこれまでに試したことを私たちに示すことをお勧めします。私たちはあなたのためにすべての課題を解決するわけではありません。 – luk2302

+0

@ luk2302 OPはすべてここに表示されています(https://stackoverflow.com/questions/45598271/java-php-preg-match)。 –

+0

に従ってください。文字列= "医師は、第二次世界大戦の間に日本で多くのがん関連問題を発見しました。 正規表現アプローチ1: - \\ bcancer \\ W +:{1,6} \\問題 正規表現アプローチ2 B(\\ + \\ 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

これは実際に受け入れられます。私はいくつかの良いアプローチを持っているかもしれません。それは実際には良いです。エリトリアンに感謝 – sunone5