-3

For example,

String a = "cat dog monkey";
String b = "cat cow monkey";
String c = "cat dog duck";

I wonder whether is there any fast and efficient way to do it in Java, in order to find the intersected words of multiple strings, in this case will be "cat".

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Xitrum
  • 7,765
  • 26
  • 90
  • 126
  • 1
    I'd say split the strings then do something like http://stackoverflow.com/questions/2851938/efficiently-finding-the-intersection-of-a-variable-number-of-sets-of-strings?rq=1 – Evan Knowles May 22 '14 at 07:21
  • 1
    I'd say at least do something. – Scary Wombat May 22 '14 at 07:21
  • You must first define "intersection". Does it include both "position of text" and "Text" ? or is it only the text which you want to check? – TheLostMind May 22 '14 at 07:24

2 Answers2

7

I'd split each string to an array, convert it to a Set and use the retainAll method:

String a = "cat dog monkey";
String b = "cat cow monkey";
String c = "cat dog duck";

Set<String> aSet = new HashSet<>(Arrays.asList(a.split(" ")));
Set<String> bSet = new HashSet<>(Arrays.asList(a.split(" ")));
Set<String> cSet = new HashSet<>(Arrays.asList(a.split(" ")));

Set<String> result = new HashSet<>(aSet);
result.retainAll(bSet);
result.retainAll(cSet);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1
  1. If you know word exists at start of the string you can use method a.startsWith("cat")
  2. If you know word exists at end of the string you can use method a.endsWith("cat")
  3. If it is anywhere in the string a.contains("cat"), but that would be case sensitive.
  4. You can use Regular Expressions also , to find it in any place.

To find intersection , here is a code example already given

[Intersection of two strings in Java

Community
  • 1
  • 1
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55