Question: I have some strings defined in my Java application, like so:

```
 m3 = "T, V, E";
 m2 = "T, W, E";

```

as an example.

Now I need to check, which parts of the strings match. So in this case, I would want a string `m4`, containing `T, E`, as a result.

In that case for example:

```
m1 = "A, S";
m3 = "T, V, E";

```

i would want an empty (but declared) string.

Or is there a better way, to do it with another method then with strings? I'm actually declaring those strings by hand. Would an array be better? If yes, how could I do it with arrays?

Answer: 
You can achieve this in many ways. One of the ways is using **Set**.

First, split **m1** the characters by (comma) and add it to **HashSet**. Then split the **m2** characters and add it to **ArrayList**. Now by the for loop try to add the **ArrayList** characters to **HashSet**. You will get false from the add method (`Set.add()`) if it is not added (because the character is already there). If you get false print the character or add it to another ArrayList.

```
        String m3 = "T, V, E";
        String m2 = "T, W, E";

        Set<String> set = new HashSet<>(Arrays.asList(m3.split(",")));
        List<String> list = Arrays.asList(m2.split(","));
        for (String s : list) {
            if (!set.add(s)) {
                System.out.println(s);
            }
        }

```

Result will be T and E
you can use the split() function as the following

```
String a="A, B, C, D";
        String b="B, C, D";
        String[] a_chars =a.split(", "); //returns array with A B C D
        String[] b_chars =b.split(", "); //returns array with B C D

```

this whay you have 2 arrays of strings now you can compare them using 2 (for) loops

```
String result="";
        for(int c=0;c<a_chars.length;c++)
        {
            for(int d=0;d<b_chars.length;d++)
            {
                if(a_chars[c].equals(b_chars[d]))
                {
                    result+=a_chars[c]+", ";
                }
            }
        }

```

now you have the result string like this `result="B, C, D, "`

check of the length of result is greater than zero 
if so erase the lase 2 characters which are `,` 

```
if(result.length()>0)result=result.substring(0,result.length()-2);

```

if the length of the result string is zero that means there is no matching letters so no need to modify it