0

I've been racking my brain for the past hour wondering how to do this. It's more of a logic question than a technical question I think.

I have two strings and wish to count how many characters they have in common. I.e Emily + Andy = 1.

I thought I could maybe convert the strings to char arrays and use two For statements within each other to go through each possibility, but I'm not 100% on how I'd do that. I've scoured Google for an answer but I'm not getting anywhere.

I apologize for not providing any code, I don't currently have any. I'm fairly new to Java and I'm not sure how to go about this.

Anyone have a solution?

CitizenSmif
  • 103
  • 1
  • 3
  • 12
  • 2
    For the input Emilyy and Andyy, are you expecting 2 or 1 as the result? How about for Emilyy and Andy? – Chetter Hummin Mar 21 '12 at 04:07
  • This looks like a homework. The approach you described will give a result, though there may be more optimal solutions. – Jayan Mar 21 '12 at 04:08
  • Amit, tbh it doesn't matter that much, I'd prefer it to return 1 though. Jayan - not homework, I'm trying to get more familiar with Android/Java, I'm writing a gimmicky 'personality matching app' and this will be part of the 'formula' – CitizenSmif Mar 21 '12 at 04:12
  • @CitizenSmif: Well is it different from this question : http://stackoverflow.com/questions/4448370/intersection-of-two-strings-in-java – Jayan Mar 21 '12 at 06:21

8 Answers8

3

First you have to remove duplicate letters in both strings, and then you have to compare. The below code is working fine.

public class CountDuplicates {

    /**
     * Author Krishnan
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String str1 = "palani";
        String str2 = "krishnan";
        String str11 = "";
        String str12 = "";
        char[] ch1 = str1.toCharArray();
        char[] ch2 = str2.toCharArray();
        int count = 0;
        for(int i=0; i<ch1.length; i++)
        {
            if(!str11.contains(ch1[i]+""))
            {
                str11 += ch1[i];
            }
        }
        for(int i=0; i<ch2.length; i++)
        {
            if(!str12.contains(ch2[i]+""))
            {
                str12 += ch2[i];
            }
        }   
        char[] ch11 = str11.toCharArray();
        char[] ch12 = str12.toCharArray();
        for(int i=0; i<ch11.length; i++)
        {
            for(int j=0; j<ch12.length; j++)
            {
                if(ch11[i] == ch12[j])
                {
                    count++;
                }
            }
        }
        System.out.println("Duplicate Letters: " + count);
    }

}

Output:

Duplicate Letters: 3

krishnan
  • 141
  • 4
1

You can convert each string to a set and then do a set intersection to find out how may characters are in common. That might be easier to understand.

Gangadhar
  • 1,893
  • 9
  • 9
1

This definitely sounds like a homework assignment... But if it is not, I would solve this by converting the strings to character arrays and writing a nested for loop that compares each character and increments a counter when a match is found. If you are only counting each letter once then the algorithm will change a bit.

mcottingham
  • 1,926
  • 2
  • 18
  • 28
1
    String s1 = "abbccsartcc";
    String s2 = "cbdcezxrtcc";
    Set arrSet1 = new HashSet(convertToList(s1));
    Set arrSet2 = new HashSet(convertToList(s2));
    arrSet1.retainAll(arrSet2)
    System.out.println("Similar characters-->" + arrSet1.size());

convertToList method:

private static List convertToList(String str) {
    List tempList = new ArrayList();
    char[] arr = str.toCharArray();
    for (char a : arr) {
        tempList.add(String.valueOf(a));
    }
    return tempList;
}

This will work perfectly !!!! HTH !!

Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
0

You could iterate over the first string putting each character as key into a Hashtable with the value of 0.

Iterate over the second string and if the character is in the hashtable, replace its value with 1.

Iterate over the hashtable and add your values.

rayd09
  • 1,837
  • 17
  • 20
0

Below method will print common character in two different string.

   public void compareString(String s1, String s2)    {
       List<Character> charList = new ArrayList<Character>();
    int count = 0;
    for(char c : S1.toCharArray()) {
        if(!charList.contains(c)) {
            INNER: for(char c1 : S2.toCharArray()) {
                if(c == c1) {
                    count = count+1;
                    charList.add(c);
                    System.out.println(c1);
                    break INNER;
                }
            }
        }
    }
    System.out.println("Duplicated Characters in two different strings :"+count);
  }
kandarp
  • 4,979
  • 11
  • 34
  • 43
  • if both strings contain a repeated character, say 'a' twice, it will give a count of 4, and print 'a' 4 times, which I thing is incorrect. – gbulmer Mar 21 '12 at 04:38
  • Thanks to notify my mistake. I had modified code as per your suggestions. Thanks again gbulmer – kandarp Mar 21 '12 at 04:51
0

This looks like homework.

A traditional approach, which applies in most languages, is:

  1. convert the strings to char arrays
  2. sort the arrays, into increasing order
  3. if necessary remove duplicates, either using a dummy value, and resorting, or shuffle them up, this is one reason to sort
  4. iterate along the arrays in one while loop, using i and j:
    when a[i] > b[j], increment j,
    when a[i] < b[j], increment i,
    otherwise you have a match, output it, save it in an array, or just count it, and increase i & j
  5. leave the loop when one array is exhausted, i > last element of a, or b > last element of b

Done

gbulmer
  • 4,210
  • 18
  • 20
0

You can use an ArrayList to solve this problem as follows, I just put this together real quick but it should be a good start:

    import java.util.ArrayList;

    public class StringCount {

/**
 * @param args
 */
public static void main(String[] args) {

    // Get the strings from the command line or pass into method.
    String name1 = "Emyyilyyyyy";
    String name2 = "Andyyyy";
    int count = 0;

    ArrayList<String> cache = new ArrayList<String>();


    for (int i = 0;i < name1.length();i++)
    {
        String check = name1.substring(i, i+1);
        System.out.println("Letter to check: " + check);
        if (name2.indexOf(check) != -1)
        {
            // Check to see if we already found the character so we don't count it again
            if (!cache.contains(check))
            {
                System.out.println("Found: " + check + " in: " + name2);
                cache.add(check);
                count++;
            }
        }

    }
    System.out.println();
    System.out.println("Count = " + count);



    }

    }
tronmcp
  • 346
  • 1
  • 6