Frequently Asked Java Programs 31 – Java Program to Find Common Characters in Two Given Strings

Hello Folks,

As part of Frequently Asked Java Programs In Interviews For Freshers And Experienced, in this post we will see a java program Find Common Characters in Two Given Strings.

Problem Statement:-

String s1= “ABCDEF”

String s2= “DEFXYZ”

Output: DEF

Solution:-

This problem can be solved with or without using collection concepts in Java. I will explain both solutions here because in interview, you could be asked in any ways.

Without Collection Concept:-

  1. We need to iterate char by char a given string with smaller length.
  2. Take the first char of a string say S1 and check if String say S2 contains that char. If yes, store in another resultant String. Repeat the same process for each char of S1.
  3. After completion of iteration, resultant string will have common characters in both Strings.

Java Program:


package StringPrograms;

import java.util.Scanner;

public class CommonCharInTwoStrings {

	public static String commonChars(String str1, String str2) {
		StringBuilder commonChars = new StringBuilder();

		if (str1.length() > 0 & str2.length() > 0) {
			// We should iterate the smallest string in length.
			String toBeIterated = (str1.length() > str2.length() ? str2 : str1);
			// Once string to be iterated is finalized, get string to be checked
			String toBeChecked = toBeIterated.equals(str1) ? str2 : str1;
			System.out.println("String to be iterated: " + toBeIterated);
			System.out.println("String to be checked: " + toBeChecked);

			// Iterating a string char by char
			for (int i = 0; i < toBeIterated.length(); i++) {
				// Check for common char
				if (toBeChecked.contains(Character.toString(toBeIterated.charAt(i)))) {
					// If contains append it to resultant string
					commonChars.append(Character.toString(toBeIterated.charAt(i)));
				}
			}
			return commonChars.toString();
		} else
			return "";
	}

	public static void main(String[] args) {

		// User input for the string to know length
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter the first string");

		String string1 = sc.nextLine();

		System.out.println("Please enter the second string");

		String string2 = sc.nextLine();

		sc.close();

		System.out.println("Output is :" + commonChars(string1, string2));
	}

}

Output:-

Please enter the first string
ABC
Please enter the second string
ABCDEF
String to be iterated: ABC
String to be checked: ABCDEF
Output is :ABC
======================================================

Please enter the first string
selenium
Please enter the second string
winium
String to be iterated: winium
String to be checked: selenium
Output is :inium

With Collection Concept:-

  1. Create a Collection List of given Strings.
  2. Find the intersection of both the lists. Intersection will be common characters.

Java Program:


package StringPrograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CommonCharInTwoStringsWithCollection {

	public static String commonChars(String str1, String str2) {

		if (str1.length() > 0 & str2.length() > 0) {

			// Adding each char of string in to a list.
			// If you want distinct chars, you can use set.
			List s1 = new ArrayList<>();
			List s2 = new ArrayList<>();

			for (int i = 0; i < str1.length(); i++) {
				s1.add(str1.charAt(i));
			}

			for (int i = 0; i < str2.length(); i++) {
				s2.add(str2.charAt(i));
			}

			// Finding intersection of both lists
			s1.retainAll(s2);

			// FOrming string from intersected chars
			StringBuilder sb = new StringBuilder();

			for (Character c : s1) {
				sb.append(c);
			}

			return sb.toString();

		} else
			return "";
	}

	public static void main(String[] args) {

		// User input for the string to know length
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter the first string");

		String string1 = sc.nextLine();

		System.out.println("Please enter the second string");

		String string2 = sc.nextLine();

		sc.close();

		System.out.println("Output is :" + commonChars(string1, string2));
	}

}


Output:

Please enter the first string
abcdef
Please enter the second string
abc
Output is :abc

You can run above program for multiple inputs and if it fails for any condition, let me know.

#HappyCoding

Leave a Reply

Your email address will not be published. Required fields are marked *