Find Common Characters Between Two Strings in Java
Finding common characters between two strings means identifying characters that appear in both strings.
This problem is frequently asked in interviews and helps strengthen string traversal, nested loops, and logical filtering.
Understanding the Problem
Given two strings:
- Compare characters of the first string with the second.
- Print characters that exist in both strings.
- Avoid printing duplicates.
Example 1
Input:
- String 1: programming
- String 2: gaming
Output: g m i n
Example 2
Input:
- String 1: hello
- String 2: world
Output: l o
Logic Explanation
- Traverse the first string character by character.
- For each character, check if it exists in the second string.
- Ensure the character has not already been printed.
- Print only unique common characters.
Java Program to Find Common Characters
import java.util.Scanner;
public class CommonCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
System.out.print("Common characters: ");
for (int i = 0; i < str1.length(); i++) {
char ch = str1.charAt(i);
// Skip already processed characters
if (str1.indexOf(ch) != i) {
continue;
}
for (int j = 0; j < str2.length(); j++) {
if (ch == str2.charAt(j)) {
System.out.print(ch + " ");
break;
}
}
}
}
}
Sample Output
Enter first string: programming
Enter second string: gaming
Common characters: g m i n
Important Notes
- Duplicate characters are printed only once.
- Comparison is case-sensitive.
- No extra data structures are used.
Practice Challenges
- Print common characters ignoring case.
- Count the number of common characters.
- Find common characters using frequency arrays.
This problem improves understanding of nested loops and string comparison logic in Java.