Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to find common words in two strings with Java

1 Answer

0 votes
import java.util.HashSet;
import java.util.Set;

public class CommonWords {

    /**
        Normalize a string:
        - Convert to lowercase
        - Replace any non-letter with a space
        This ensures consistent word comparison.
    */
    private static String normalize(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c)) {
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(' ');
            }
        }
        return sb.toString();
    }

    /**
        Extract words from a string.

        This function:
        - Normalizes the input
        - Splits on whitespace
        - Filters out empty entries
        - Returns a Set<String> for fast lookup and automatic duplicate removal
    */
    private static Set<String> extractWords(String s) {
        String normalized = normalize(s);
        String[] parts = normalized.split("\\s+");

        Set<String> words = new HashSet<>();
        for (String w : parts) {
            if (!w.isEmpty()) {
                words.add(w);
            }
        }
        return words;
    }

    /**
        Find common words between two strings.

        This function:
        - Extracts words from both strings
        - Uses set intersection for efficiency
        - Returns a new Set<String> containing the common words
    */
    private static Set<String> findCommonWords(String a, String b) {
        Set<String> wordsA = extractWords(a);
        Set<String> wordsB = extractWords(b);

        Set<String> common = new HashSet<>(wordsA);
        common.retainAll(wordsB); // efficient set intersection
        return common;
    }

    public static void main(String[] args) {
        String s1 = "The quick brown fox jumps over the lazy dog.";
        String s2 = "A lazy dog sleeps while the quick fox runs away.";

        Set<String> common = findCommonWords(s1, s2);

        System.out.println("Common words:");
        for (String w : common) {
            System.out.println(w);
        }
    }
}


/*
run:

Common words:
the
quick
lazy
dog
fox

*/

 



answered Sep 11 by avibootz
...