I need to create a function that returns a number with the amount of characters in common among one string and a vector of them.

public int sameChars (Vector<String> otherStrs){
        int result = 0;
        String original = "aab";
        for (int i=0; i< original.length(); i++) {
            char aux = original.charAt(i);
            String targetStr = otherStrs.get(i);
            for (int j=0; j< targetStr.length(); j++) {
                char targetAux = targetStr.charAt(j);
                if (aux.compareTo(targetAux) == 0) {
                    result++;
                }
            }
        }
        return result;
    }

3 problems in this initial stage:
- Getting error on compareTo, char cannot be dereferenced.
- I need to distinguish 'A' from 'a'. Equals doesnt do it.
- I need to account only for 1 of each character type. ("aab" compared to "ababababba" should only give a total count of 2.

Help is appreciatted to the newbie :)

Recommended Answers

All 3 Replies

1. char is a numeric type, not some kind of String, so you don't (can't) use .equals(). You can just compare them as numerics (char1 == char2).
2. Wrong. 'A' and 'a' are different chars and are not equal.
3. When you get a match break out of the appropriate loop(s).

Just an update, the 1st problem was resolved by switching from char to Character.

And, the 2nd FOR statment has to be replaced with:

(int j=0; j< Math.min(original.length(), targetStr.length()); j++)
public int sameChars (Vector<String> otherStrs){
        int result = 0;
        String original = "aab";
        for (int h= 0; h< otherStrs.size(); h++) {
            String targetStr = otherStrs.get(h);
            for (int i=0; i< original.length(); i++) {
                char aux = original.charAt(i);
                for (int j=0; j< Math.min(original.length(), targetStr.length()); j++) {
                    char targetAux = targetStr.charAt(j);
                    if (aux == targetAux) {
                        result++;
                        break;
                    }
                }
            }
        }
        return result;
    }

Kind of expensive with 3 for cycles but not a problem.

All is working but im getting multiple counts for same chars, breaking the cycle isn't enough.

I ran it with original string "aba" and the other string as "avr" and got 2 as the result. Any idea?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.