What Are Anagrams in Java

According to Wikipedia, an anagram is a word or phrase formed by rearranging the letters of a different word or phrase. We can generalize this in string processing by saying that an anagram of a string is another string with exactly the same quantity of each character in it, in any order.

How do you write an anagram in Java?

  1. import java.util.Arrays;
  2. public class AnagramString {
  3. static void isAnagram(String str1, String str2) {
  4. String s1 = str1.replaceAll(“\\s”, “”);
  5. String s2 = str2.replaceAll(“\\s”, “”);
  6. boolean status = true;
  7. if (s1.length() != s2.length()) {

Is anagram a method in Java?

The best way to check for two strings to be Anagram is to convert them to a character array (String#toCharArray) . Then sort them using Arrays. sort method. And do the comparison on them.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest