Advertisement
Guest User

Chapter 7 Anagram

a guest
Sep 18th, 2014
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. //Rafal Bielech
  2. //CSCI 401
  3. //Ch 7 homework Anagram
  4. import java.util.Scanner;
  5. import java.util.Arrays;
  6. public class Anagram {
  7.      
  8.     public static boolean isAnagram(String a, String b){
  9.         //method to convert string to all lower case
  10.         String a1= a.toLowerCase();
  11.         String b1= b.toLowerCase();
  12.        
  13.         //convert string to char array
  14.         char[] arra = a1.toCharArray();
  15.         char[] arrb = b1.toCharArray();
  16.        
  17.         //sort it alphabetically
  18.         Arrays.sort(arra);
  19.         Arrays.sort(arrb);
  20.        
  21.         //method that checks if there are same character at the same places in 2 arrays , if not sorted then might yield false
  22.         boolean result = Arrays.equals(arra, arrb);
  23.         return result;}
  24.        
  25.     public static void main(String[] args) {
  26.         // TODO Auto-generated method stub
  27.         Scanner input = new Scanner (System.in);
  28.         System.out.println("Enter the first string:");
  29.         String a = input.nextLine();
  30.         System.out.println("Enter the second string:");
  31.         String b = input.nextLine();
  32.        
  33.                                      //if result true, print this       //if result false, print this
  34.     System.out.print(isAnagram(a,b)? "The two strings are anagrams": "The two strings are not anagrams");
  35.        
  36.     }}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement