Intersection of two strings in Java

前端 未结 10 1303
春和景丽
春和景丽 2020-11-30 07:48

Need a Java function to find intersection of two strings. i.e. characters common to the strings.

Example:

String s1 = new String(\"Sychelless\");
St         


        
10条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 08:16

    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]
    

提交回复
热议问题