Java Program to Check for Anagrams Between Two Strings

Отвечено с помощью: GPT-4o-mini отJava Q&A Hub

Вопрос:

Write a Java program to check if the two strings are anagrams.

Ответ:

Certainly! An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. To check if two strings are anagrams in Java, you can follow these steps:

  1. Remove any whitespace and convert both strings to the same case (e.g., lowercase).
  2. Sort the characters of both strings.
  3. Compare the sorted strings.

Here’s a simple Java program that implements this logic:

import java.util.Arrays;
import java.util.Scanner;

public class AnagramChecker {

    public static boolean areAnagrams(String str1, String str2) {
        // Remove whitespace and convert to lowercase
        str1 = str1.replaceAll("\\s+", "").toLowerCase();
        str2 = str2.replaceAll("\\s+", "").toLowerCase();

        // If lengths are not the same, they cannot be anagrams
        if (str1.length() != str2.length()) {
            return false;
        }

        // Convert strings to character arrays
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();

        // Sort the character arrays
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        // Compare sorted arrays
        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first string: ");
        String firstString = scanner.nextLine();

        System.out.print("Enter the second string: ");
        String secondString = scanner.nextLine();

        if (areAnagrams(firstString, secondString)) {
            System.out.println("The strings are anagrams.");
        } else {
            System.out.println("The strings are not anagrams.");
        }

        scanner.close();
    }
}

How to Run the Program:

  1. Copy the code into a file named AnagramChecker.java.
  2. Compile the program using the command: javac AnagramChecker.java.
  3. Run the program using the command: java AnagramChecker.
  4. Input two strings when prompted, and the program will tell you if they are anagrams.

Example:

  • Input: listen and silent

  • Output: The strings are anagrams.

  • Input: hello and world

  • Output: The strings are not anagrams.

This program effectively checks for anagrams by sorting the characters of both strings and comparing them.