2015-06-25 43 views
-2

我有一個字符串s1(包​​含很多英語句子),一個字符串l1列表(其中包含像巴士,房子,火車,火車引擎,火車引擎的生活字數不會大於3)等)以及字符串l2(類似於l1)和整數n的列表。如何檢測字符串中的n個短語或單詞

對於l1的每個元素,我必須在s中找到l1或l2的其他元素(l1的元素可以在s中多次出現,我們必須在每次出現時找到它),以使它們的距離(距離是例如:我有xyz。在這種情況下,I和xyz之間的距離是2),從l1的元素的距離小於或等於l1元素兩邊的n。這些單詞/短語(l1或l2的元素)將被存儲在java中的列表中。

e.g.: 
Input: 
s= i am asd fgh and studying in zxc vbn bnmkl. i am 100 years old.(may contain other symbols too) 
l1= i 
l2=asd, fgh, zxc, vbn 
n=3. 

Output: 
asd,fgh,zxc,vbn 



       for(int j=0;j<l1.size();j++){ 
        String s1=l1.get(j); 
        int index = s.indexOf(s1); 
        while(index >= 0) { 
         System.out.println(index); 
         for(int k=0;k<n;){ 
          // how to detect the words before and after that element of l1 such that distance is <= n on either side in a passage and they are contained in either l1 or l2. 
         } 
        index = s.indexOf(s1, index+1); 
        } 
       } 

任何人都可以幫助我如何實現這個?

+0

我們不會爲您生成代碼。開始編碼。回過頭來,當你有一些代碼並且詢問你不明白的部分的具體問題時。 – Turing85

+0

你應該看看正則表達式。 –

+0

我已添加代碼並在需要幫助的地方添加了該部分(作爲註釋)。 – Sam

回答

0

谷歌是你最好的朋友。這也是一個非常簡單的函數,可以用不同的方式來解釋。

使用循環(for,foreach,while)可能有用,下面的鏈接就是這樣的例子。 Find specific word in text file and count it & & Count the number of Occurrences of a Word in a String

現在你有一個搜索功能,問題是如何以多個濾波器設置。


下面是一個普通的例子

如果S2是成爲一個字符串數組例如

string[] table = s2.split(' '); // this would do that 

,那麼你可以通過每個過濾器,像這樣使用一個for循環循環:

for (int i = 0; i < table.length(); i++) 
{ 
    string filter = table[i]; //this would get the filter of the current loop 
    // search function here as well as your counters (refer to examples provided) 
} 

這裏是另一個例子

String table_filter = l2.split(" "); //this would split your filter string into an array (at every space) String table_s = s.split(" "); 
//this would split your string into an array (at every space) 

for (int i = 0; i < table_filter.size(); i++){  
for (int j = 0; j < 
table_s.size(); j++) 
    {  
    // do stuff (like comparing if this = that then do this or using a switch)} 
+0

我意識到,在Java中,分裂是不同於C#,你將不得不搜索如何將字符串拆分爲表,只需在Google中鍵入「Java split()」,您將擁有數百個示例 – Viralwarrior012

+0

我有添加了代碼並添加了我需要幫助的部分。你的解決方案中的問題是,s是一個可以包含'。',','等符號的通道,它們可以作爲分隔符。 – Sam

+0

在java中分割字符串:http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java – Viralwarrior012

相關問題