benny benny - 1 year ago 88
Java Question

Java: find common characters in two strings

I'm asked to write a program that finds the common characters in two strings using the indexOf(char) method and a for loop. Here's what I have so far - the output comes out blank still.

import java.util.Scanner;
public class ClassName {
public static void main (String args []) {

Scanner input = new Scanner (;

String a = "";
String b = "";
String c = "";

System.out.print("Enter two words: ")
a = input.nextLine();
b = input.nextLine();

for (int i = 0; i < a; i++){

char ch = a.charAt(i);
if (b.indexOf(ch) != -1){
c = c+String.valueOf(ch);
System.out.print("Common letters are: "+c);


output here

I'm not sure where to go from here.


Answer Source

Your code will duplicate common characters for example if you compare "developper" to "programmer" your result string will contain three time the e character

If you don't want that behaviour I suggest that you also use a Set like this:

public class CommonCharsFinder {

    static String findCommonChars(String a, String b) {
        StringBuilder resultBuilder = new StringBuilder();
        Set<Character> charsMap = new HashSet<Character>();
        for (int i = 0; i < a.length(); i++) {
            char ch = a.charAt(i); //a and b are the two words given by the user
             if (b.indexOf(ch) != -1){

        Iterator<Character> charsIterator = charsMap.iterator();
        while(charsIterator.hasNext()) {
        return resultBuilder.toString();
    // An illustration here
    public static void main(String[] args) {
       String s1 = "developper";
       String s2 = "programmer";

       String commons = findCommonChars(s1, s2);
       System.out.println(commons);     }


Result from the example:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download