Question

  static boolean contains(Iterable<String> haystack, String needle) {
    for (String s : haystack) {
        if (s.contains(needle)) {
        return true;
      }
    }
    return false;
  }

  static void containsAll() throws IOException {
    List<String> words = loadLines("opacial.txt");
    List<String> tocheck = loadLines("queries0.txt");
    System.out.println(words.size());
    System.out.println(tocheck.size());
    int index2 = 0;
    for (String s : tocheck) {
      if (contains(words, s)) {
          index2++;
          //return false;

      }

     }
    System.out.println(index2);
    //return true;
  }

i am looking a method like contains (code above) that will do this: it will check if needle exists in the haystack, or if needle is part of a string in haystack. In that case (the code above) if i reverse the file that goes to haystack, and the file that gives the needle, the result is the same. but i dont want that. for example:

File 1: 
i love beers
i like travelling
stackoverflow
beers

And File2 :    
beers
i love stackoverflow

then if haystack comes from file 1 and needle comes from file2, i want the result to be 2 because the word beers is part-or the same only with two strings of haystack. (beers ---> i love beers and beers) - nothing happens with i love stackoverflow) BUT when haystack comes from file2 and needle comes from file1, i want the result to be 2. (i love beers is not part or same with anything of file 2, i like travelling the same, stackoverflow is part of i love stackoverflow -1- and finally beers is same with beers -2-) what is the correct method for that? As i said before contains gives me the same result no matter what file is haystack or gives the needle's strings.

PS in my example the result is the same, but i think that is random.

how can i do that?

Was it helpful?

Solution

I think that you meant that the values should probably be different for the two cases? You show them as being the same.

If you want to find a string within another string, use the String object's indexOf method. For example:

String s = "abcdef";
s.indexOf("b");

will return 1. If the value is not present, the method returns -1.

So if you want to find a needle in a haystack, it means checking every line one file for the existence of a line in another file. Keep in mind that if the files (and the lines in them) are large, this means a lot of string processing, which can be slow. And you would have to do it in both directions. First, get a line in file 1, and compare it to every line in file 2 (unless you find a match, in which case you can stop looking for the line from file 1). Then move to the next line in file 1, etc.

The reverse, and look for line 1 from file 2 in file 1.

I won't describe all the logic, but that part shouldn't be too hard to figure out, assuming you know how to open files and write loops.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top