0

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?

nameless
  • 1,483
  • 5
  • 32
  • 78
  • 5
    what have you got so far? this is just your assignment – Stultuske Sep 08 '17 at 07:31
  • @Stultuske I tried like using substr() to check, but basically thats not what I want because I need the "single letters" to be checked (seperated by a comma) and not the "string" – nameless Sep 08 '17 at 07:33
  • 3
    it sounds like you want the intersection of two sets. (there is a collection class for Set) – Patrick Parker Sep 08 '17 at 07:34
  • by thinking again, it might be better to declare those variables as arrays of characters. But is there then a way to check, which array elements match? – nameless Sep 08 '17 at 07:36
  • or @PatrickParker how could I do that? – nameless Sep 08 '17 at 07:36
  • Are these strings always delimited by commas? If so, you can easily check it. – Jay Sep 08 '17 at 07:37
  • Just convert your strings in Set of char. it will be easier if you have those strings declarated in arrays. Check here : https://stackoverflow.com/questions/2400838/efficient-intersection-of-two-liststring-in-java – JulienCsj Sep 08 '17 at 07:37
  • @Jay yes, and thats why I thought arrays might make more sence, because I don't need to `split` the strings first, but still I don't know how to check if they contain the same values then – nameless Sep 08 '17 at 07:38
  • You can use array if the both strings arrays are same length then you can match value of each index of both string. if values matches then assign that value to new array. – Zaigham Raza Sep 08 '17 at 07:39
  • @ZaighamRaza every array might have another length (which is between 1 and 3) – nameless Sep 08 '17 at 07:41
  • @nameless then don't use array because it will costly due to multiple checks then use java split function to split that words by adding (,- etc) such indicators to each word of your array to split. – Zaigham Raza Sep 08 '17 at 07:44

6 Answers6

4

In Java 8 you can proceed as below :

    String s1 = "T,V,E";
    String s2 = "T,W,E";

    List<String> l1 = Arrays.asList(s1.split(","));
    List<String> l2 = Arrays.asList(s2.split(","));

    List<String> result = l1.stream().filter(l2::contains).collect(Collectors.toList());

    System.out.println(String.join(",", result));

The result is "T,E" as expected.

mabad
  • 51
  • 4
1

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

Bhuvanesh BS
  • 13,474
  • 12
  • 40
  • 66
1

The appropriate data structure is Set.

    Set<String> m3 = new TreeSet<>();
    Collections.addAll(m3, "T", "V", "E");
    Collections.addAll(m3, "T, V, E".split(",\\s*")); // Alternatively.

    Set<String> m2 = new HashSet<>();
    Collections.addAll(m2, "T", "W", "E");

    Set<String> m5 = new TreeSet<>(m2);
    m5.retainAll(m3);

Java 9:

    Set<String> m3 = Set.of("T", "V", "E");
    Set<String> m2 = Set.of("T", "W", "E");
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

If all your String follows this pattern : ..., ..., .... , you could split them and filter only each String that is contained in the two arrays.
You can then collect them into a List and join them with , :

List<String> commonStrings = Arrays.stream(m2.split(",\\s"))
      .flatMap(s-> Arrays.stream(m3.split(",\\s"))
      .filter(s2.equals(s)))          
      .collect(Collectors.toList());

String joinedString = String.join(",", commonStrings);

Note that this code doesn't return the exact number of equals occurrences in the two Strings.
So if one String contains two A and the other one A, you will get two A in the result.
If it doesn' matter and you want to get only distinct String, you can invoke distinct() before collect().

Otherwise, to return the exact number of equals occurrences, during the processing, as soon as a String part is consumed (A for example) as the two parts are equal in the two Strings, you could create new Strings from the actual Strings but by removing this String part .

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

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

Ahmed Rajab
  • 603
  • 3
  • 10
  • 28
0

String s1 = "T,V,E"; String s2 = "T,W,E";

List<String> l1 = Arrays.asList(s1.split(","));
List<String> l2 = Arrays.asList(s2.split(","));

List<String> result = l1.stream().filter(l2::contains).collect(Collectors.toList());

System.out.println(String.join(",", result));

result = T&E This is good answer I will tell you too this