Count common characters presented array strings

Count common characters presented array strings

Write a program that gives count of common characters presented in an array of strings or array of character arrays

For example: For the following input strings:

aghkafgklt
dfghako
qwemnaarkf

The output should be 3. because the characters a, f and k are present in all 3 strings.

Note: The input strings contains only lower case alphabets

Solution: Please have java program below:

package com.javahonk;

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

public class CountOfCommonCharacters {

    public static void main(String[] args) {

        String first = "aghkafgklt";
        String first2 = "dfghako";
        String first3 = "qwemnaarkf";

        char array1[] = first.toCharArray();
        Set<String> set = new HashSet<String>();

        for (int i = 0; i < array1.length; i++) {
            char c = array1[i];
            if (first.indexOf(c) != -1 && first2.indexOf(c) != -1
                    && first3.indexOf(c) != -1) {
                set.add(String.valueOf(c));
            }

        }

        System.out.println("Common characters present in string");
        for (String string : set) {
            System.out.println(string);
        }

    }

}

Output:

Count common characters presented array strings

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *