Christian Walter Christian Walter - 2 years ago 70
Java Question

compare elements of two strings java

I want to check if one string contains a specific length of char-sequence in another string, f.e.

String user1_hobbies = "friends, cinema/outside"
String user2_hobbies = "outside, going out with friends"
boolean check;

if (user1_hobbies.contains(user2_hobbies)){
check = true;
} else
{check = false
}


ofc this attempt doesn't work because the whole string must contain the whole char-sequence. I just want to check, if only parts of both string will match... in this case it shall match because "friends" or "outside" are matching.

Answer Source

Following the tip from @JBNizet, you could create two sets of words for the two sentences and then check to see if the intersection between the two sets be non-empty:

Set<String> set1 = new HashSet<String>(Arrays.asList(user1_hobbies.split(" ")));
Set<String> set2 = new HashSet<String>(Arrays.asList(user2_hobbies.split(" ")));
set1.retainAll(set2);

if (set1.size() > 0) {
    System.out.println("There was a match.");
}
else {
    System.out.println("There were no matches.");
}

You might want to first remove any extraneous punctuation you might have, such as commas or slashes. There could be even more work required in addition in your actual problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download