How to find and print the common characters (letters) in different strings with Java

2 Answers

0 votes
public class MyClass {
    public static String getCommonCharacters(String str1, String str2) {
	    int str1size = str1.length();
        int str2size = str2.length();
		String strcommon = "";

        for (int i = 0; i < str1size; i++) {
            for (int j = 0; j < str2size; j++) {
                if (str1.charAt(i) == str2.charAt(j) && str1.charAt(i) != ' ') {
                    strcommon += str1.charAt(i);
                }
            }
        }
 
        StringBuilder sb = new StringBuilder();
        strcommon.chars().distinct().forEach(ch -> sb.append((char) ch));

		return sb.toString();
	}
	
    public static void main(String args[]) {
        String str1 = "c c++ c# java go";
        String str2 = "python nodejs php javascript";
        
        String strcommon = getCommonCharacters(str1, str2);
     
        System.out.println("Same letters are: " + strcommon);
    }
}
 
  
 
 
 
/*
run:
  
Same letters are: cjavo
  
*/

 



answered Jan 26, 2024 by avibootz
edited Jan 26, 2024 by avibootz
0 votes
import java.util.HashSet;
import java.util.Set;

public class MyClass {
    public static String getCommonCharacters(String str1, String str2) {
	    String strcommon = "";
 
        Set<Character> st1 = new HashSet<>();
        for (char c : str1.toCharArray()) {
            st1.add(c);
        }
         
        Set<Character> st2 = new HashSet<>();
        for (char c : str2.toCharArray()) {
            st2.add(c);
        }
 
        st1.retainAll(st2);  
 
        for (char ch : st1) {
            strcommon += ch;
        }

		return strcommon;
	}
	
    public static void main(String args[]) {
        String str1 = "c c++ c# java go";
        String str2 = "python nodejs php javascript";
        
        String strcommon = getCommonCharacters(str1, str2);
     
        System.out.println("Same letters are: " + strcommon);
    }
}
 
 
 
 
 
 
/*
run:
  
Same letters are:  acvjo
  
*/

 



answered Jan 26, 2024 by avibootz
edited Jan 26, 2024 by avibootz
...