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.
String s1= “ABCDEF”
String s2= “DEFXYZ”
Output: DEF
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.
- We need to iterate char by char a given string with smaller length.
- 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.
- After completion of iteration, resultant string will have common characters in both Strings.
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