I'm trying to write a code to check if two strings are anagrams. i have already figured out a code but I can't get it to work for words of different cases and words with whitespace. I would really appreciate any input
Thank you!
Here is what I have so far

import java.io.*;

public class AnagramFinder
public static boolean anagram(String a, String b)
if (a.length() != b.length()) return false;
int[] alphanum = new int[256];
int chars = 0; //no of unique characters
int num_completed_b = 0;
char[] a_array = a.toCharArray();
for (char c : a_array)
{ // count number of each char in a.
if (alphanum[c] == 0) ++chars;
for (int i = 0; i < b.length(); ++i)
int c = (int) b.charAt(i);
if (alphanum[c] == 0)
{ // if you find more of char c in b than in a return false.
return false;
if (alphanum[c] == 0)
if (num_completed_b == chars)
// it’s a match if b has been processed
return i == b.length() - 1;
return false;
public static void main (String[] args) {
System.out.println ("Enter the first string");
String string1 = "";
String string2 = "";
InputStreamReader input1 = new InputStreamReader(System.in);
BufferedReader reader1 = new BufferedReader(input1);
string1 = reader1.readLine();
catch(Exception e1){}
System.out.println ("Enter the second string");
InputStreamReader input2 = new InputStreamReader(System.in);
BufferedReader reader2 = new BufferedReader(input2);
string2 = reader2.readLine();
catch(Exception e2){}
boolean value = anagram(string1,string2);
if(value == true)
System.out.println("The string are anagrams of each other");
System.out.println("The string are NOT anagrams of each other");
}//end of main
}//end of class

Edited by Ezzaral: Added code tags. Please use them to format any code that you post.

6 Years
Discussion Span
Last Post by stultuske

You can convert both strings to the same case (eg toUpperCase() ) before checking if they are anagrams.

ps line 58 if(value == true) is redundant. if(value) is quite sufficient.


and as for the white spaces:
remove all the spaces (off course after you've made copies of the original values, if you still need them later on)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.