如何检测字符串中的n个短语或单词

时间:2015-06-25 19:51:55

标签: java arrays string arraylist

我有一个字符串s1(包​​含很多英文句子),一个字符串l1的列表(其中包含公共汽车,房屋,火车,火车引擎,火车引擎的生命等元素(单词数量从不大于3)等等)和字符串l2(类似于l1)和整数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);
                   }
               }

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

谷歌是你最好的朋友。它也是一个非常简单的功能,可以用不同的方式解释。

使用循环(for,foreach,while)可能是有用的,以下链接就是这样的例子。 Find specific word in text file and count it&amp;&amp; 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 )}