Charles Allo
Charles Allo

Reputation: 1

Narrow down common elements between strings

public class numerodetel {**strong text**    
static void commun(String tel1, String tel2){
    for(int i=0;i<tel1.length();i++){
        for(int j=0;j<tel2.length();j++){
            if(tel1.charAt(i)==tel2.charAt(j))
                System.out.printf(" %c,", tel1.charAt(i));

        }

    }
}
public static void main(String[] args){
        String telUDM = "5143436111", telJean = "4501897654";

        commun(telUDM, telJean);
    }
}

The code works and I am able to find the common numbers between the two phone numbers. Is there an easy way, though, to make it so that once a common number is detected between the two, it doesn't reappear again? In this case it would be 5, 1, 4, 6.

Upvotes: 0

Views: 51

Answers (3)

Tyl
Tyl

Reputation: 5252

Try this:

public class numerodetel {**strong text**    
static void commun(String tel1, String tel2){
    dstr="";
    for(int i=0;i<tel1.length();i++){
        if (dstr.indexOf(tel1.charAt(i)) >= 0)
            continue;
        for(int j=0;j<tel2.length();j++){
            if (tel1.charAt(i)==tel2.charAt(j)) {
                dstr += tel1.charAt(i);
                System.out.printf(" %c,", tel1.charAt(i));
            }
        }

    }
}
public static void main(String[] args){
        String telUDM = "5143436111", telJean = "4501897654";

        commun(telUDM, telJean);
    }
}

Simply updated your own codes.
It's to maintain a dumplicates string dstr here, common chars will add into it.
When a letter already in it, then will skip the comparing by continue.
indexOf will return the position of the letter in the string, or -1 if not in it.

Upvotes: 0

Andreas
Andreas

Reputation: 159086

If you don't want duplicates, use Set.

This will also perform better O(n+m), instead of the O(n*m) of your code.

static void commun(String tel1, String tel2) {
    Set<Integer> chars1 = tel1.chars().boxed().collect(Collectors.toSet());
    Set<Integer> chars2 = tel2.chars().boxed().collect(Collectors.toSet());
    chars1.retainAll(chars2);
    for (int ch : chars1)
        System.out.printf(" %c,", (char) ch);
}

Test

commun("5143436111", "4501897654");

Output

 1, 4, 5, 6,

Upvotes: 0

Eduardo
Eduardo

Reputation: 329

First you can remove the repeated numbers from the string using something like what is suggested here:

Removing duplicates from a String in Java

Then, you can use break statement to leave the inner loop every time a match is found:

static void commun(String tel1, String tel2) {
    for(int i=0;i<tel1.length();i++) {
        for(int j=0;j<tel2.length();j++) {
            if(tel1.charAt(i)==tel2.charAt(j)) {
                System.out.printf(" %c,", tel1.charAt(i));
                break;
            }
        }
    }
}

Upvotes: 1

Related Questions