📜  java anagrams - Java (1)

📅  最后修改于: 2023-12-03 15:31:28.449000             🧑  作者: Mango

Java Anagrams

Anagrams are words or phrases formed by rearranging the letters of a different word or phrase. Java Anagrams is a Java program that checks whether two strings are anagrams of each other or not.

How it works

Java Anagrams program works in the following way:

  1. The program takes two strings as input.
  2. The input strings are converted to lowercase to avoid case-sensitive comparisons.
  3. The input strings are converted to char arrays.
  4. The char arrays are sorted using the Arrays.sort() method.
  5. The sorted char arrays are compared to check if they are equal.

If the two input strings are anagrams of each other, the program returns true. Otherwise, it returns false.

Code Sample
import java.util.Arrays;

public class JavaAnagrams {
    public static boolean isAnagram(String input1, String input2) {
        if (input1 == null || input2 == null || input1.length() != input2.length()) {
            return false;
        }

        char[] input1Char = input1.toLowerCase().toCharArray();
        char[] input2Char = input2.toLowerCase().toCharArray();

        Arrays.sort(input1Char);
        Arrays.sort(input2Char);

        return Arrays.equals(input1Char, input2Char);
    }
}
Usage

You can use the isAnagram() method of the JavaAnagrams class to check whether two strings are anagrams of each other or not.

public class Main {
    public static void main(String[] args) {
        String input1 = "listen";
        String input2 = "silent";
        boolean result = JavaAnagrams.isAnagram(input1, input2);
        System.out.println("Are the two strings anagrams? " + result);
    }
}
Output
Are the two strings anagrams? true
Conclusion

Java Anagrams is a simple and efficient program to check whether two strings are anagrams of each other. This program can be useful in various applications that involve string manipulation.