Need a Java function to find intersection of two strings. i.e. characters common to the strings.
Example:
String s1 = new String(\"Sychelless\");
St
I have used TreeSet. And retainAll() in TreeSet
to get matched elements.
Oracle Doc:
retainAll(Collection> c)
Retains only the elements in this set that are contained in the specified collection (optional operation).
String s1 = new String("Sychelless");
String s2 = new String("Sydney");
Set firstSet = new TreeSet();
for(int i = 0; i < s1.length(); i++) {
firstSet.add(s1.charAt(i));
}
Set anotherSet = new TreeSet();
for(int i = 0; i < s2.length(); i++) {
anotherSet.add(s2.charAt(i));
}
firstSet.retainAll(anotherSet);
System.out.println("Matched characters are " + firstSet.toString());//print common strings
//output > Matched characters are [S, e, y]