-2

I am using the code below to find common characters in two strings. Sometimes this code produces wrong results such as giving output value which is greater than string lengths.

for(int i = 0;i < num1.length();i++){
                for(int j =0;j < num2.length();j++){
                    if(num1.charAt(i) == num2.charAt(j)){
                        count++;
                    }
                }
            }
SSH
  • 1,609
  • 2
  • 22
  • 42
suraj kiran
  • 49
  • 1
  • 1
  • 9
  • use num1.charAt(i).equals(num2.charAt(j)) instead of == for string comparison – albertoqa Jun 05 '15 at 09:00
  • 2
    @albertoqa He's comparing characters? I don't think you need `.equals`. – almightyGOSU Jun 05 '15 at 09:01
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Abdulla Nilam Jun 05 '15 at 09:01
  • Count can go beyond the length of the string in the case some characters get duplicated in either string. You might want to keep adding the duplicated characters to a set – Dev Blanked Jun 05 '15 at 09:01
  • 3
    No, the use of "equals" is not necessary. "charAt" returns a "char" value that can safely be compared using ==. – mastov Jun 05 '15 at 09:02
  • 1
    Please give a example of your expected input/output – singhakash Jun 05 '15 at 09:04
  • because of inner loop, you are getting greater results. And Count can go beyond the length of the string in the case some characters get duplicated in either string – Amit Das Jun 05 '15 at 09:23

3 Answers3

10

It's not clear what you are trying to achieve.

Your code can produce results greater than the string length because of characters that appear more than once in your strings. You can get results of up to num1.length() * num2.length().

In case you want to get the number of positions at which you have the same character in both strings, you can to that in just one loop and use the same index for the "charAt" calls on both strings:

for(int i = 0; i < num1.length() && i < num2.length(); i++) {
    if(num1.charAt(i) == num2.charAt(i)){
        count++;
    }
}

In case you want to get the number of unique letters that appear in both strings, run through both strings independently and add the letters to a set. Then intersect both sets. The number of elements in that intersection set is your result:

    Set<Character> characters1 = new TreeSet<Character>();
    for(int i = 0; i < num1.length(); i++) {
        characters1.add(num1.charAt(i));
    }

    Set<Character> characters2 = new TreeSet<Character>();
    for(int i = 0; i < num2.length(); i++) {
        characters2.add(num2.charAt(i));
    }

    characters1.retainAll(characters2);
    return characters1.size();
mastov
  • 2,942
  • 1
  • 16
  • 33
3

You can try something like this using HashSet

import java.util.HashSet;
import java.util.Set;

public class QuickTester {

    public static void main(String[] args) {

        String s1 = "happy";
        String s2 = "elephant";

        Set<Character> set1 = new HashSet<Character>();
        Set<Character> set2 = new HashSet<Character>();

        for(char c : s1.toCharArray()) {
            set1.add(c);
        }
        for(char c : s2.toCharArray()) {
            set2.add(c);
        }

        // Stores the intersection of set1 and set2 inside set1
        set1.retainAll(set2);

        for(char c : set1) {
            System.out.print(" " + c);
        }

        System.out.println("\nTotal number of common characters: "
            + set1.size());
    }
}

Refer to retainAll on how the intersection of 2 sets is done.

Input Strings:

happy
elephant

Output:

 p a h
Total number of common characters: 3
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
1

Use org.apache.commons.lang.StringUtils to count matches like this

    String num1 = "Java";
    String num2 = "Guava";
    int count = 0;
    List<String> charsChecked = new ArrayList<>();

    for(int i = 0;i < num1.length();i++){
        String charToCheck = num1.substring(i, i+1);

        if (!charsChecked.contains(charToCheck)) {
            count += StringUtils.countMatches(num2, charToCheck);
            charsChecked.add(charToCheck);
        }
    }

    System.out.println(count);

This results in the count being 3 in the above example

slarge
  • 637
  • 1
  • 7
  • 19