📅  最后修改于: 2023-12-03 15:31:28.449000             🧑  作者: Mango
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.
Java Anagrams program works in the following way:
Arrays.sort()
method.If the two input strings are anagrams of each other, the program returns true
. Otherwise, it returns false
.
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);
}
}
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);
}
}
Are the two strings anagrams? true
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.