anagram program code example

Example 1: python anagrams

# function to check if two strings are 
# anagram or not  
def check(s1, s2): 
      
    # the sorted strings are checked  
    if(sorted(s1)== sorted(s2)): 
        print("The strings are anagrams.")  
    else: 
        print("The strings aren't anagrams.")          
          
# driver code   
s1 ="listen"
s2 ="silent" 
check(s1, s2)

Example 2: anagram python

def isAnagram(A,B):
  if sorted(A) == sorted(B):
    print("Yes")
  else:
    print("No")
isAnagram("earth","heart") #Output: Yes

#Hope this helps:)

Example 3: anagram java program

// string anagram program in java
import java.util.Arrays;
public class Anagram
{
   public static void main(String[] args)
   {
      String strOne = "silent";
      String strTwo = "listen";
      // checking if two strings length are same
      if(strOne.length() == strTwo.length())
      {
         // converting strings to char array
         char[] charOne = strOne.toCharArray();
         char[] charTwo = strTwo.toCharArray();
         // sorting character array
         Arrays.sort(charOne);
         Arrays.sort(charTwo);
         // if sorted character arrays are same then the string is anagram
         boolean output = Arrays.equals(charOne, charTwo);
         if(output)
         {
            System.out.println(strOne + " and " + strTwo + " are anagram.");
         }
         else
         {
            System.out.println(strOne + " and " + strTwo + " are not anagram.");
         }
      }
      else
      {
         System.out.println(strOne + " and " + strTwo + " are not anagram.");
      }
   }
}

Example 4: check if anagram

function isAnagram(stringA, stringB) {
  // Sanitizing
  stringA = stringA.toLowerCase().replace(/[\W_]+/g, "");
  stringB = stringB.toLowerCase().replace(/[\W_]+/g, "");

  // sorting
  const stringASorted = stringA.split("").sort().join("");
  const stringBSorted = stringB.split("").sort().join("");

  return stringASorted === stringBSorted;
}

Tags:

Java Example