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

Recommended Answers

All 2 Replies

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.