Hello,
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;
++alphanum[c];
}
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;
}
--alphanum[c];
if (alphanum[c] == 0)
{
++num_completed_b;
if (num_completed_b == chars)
{
// it’s a match if b has been processed
completely
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);
try
{
string1 = reader1.readLine();
}
catch(Exception e1){}
System.out.println ("Enter the second string");
InputStreamReader input2 = new InputStreamReader(System.in);
BufferedReader reader2 = new BufferedReader(input2);
try
{
string2 = reader2.readLine();
}
catch(Exception e2){}
boolean value = anagram(string1,string2);
if(value == true)
System.out.println("The string are anagrams of each other");
else
System.out.println("The string are NOT anagrams of each other");
}//end of main
}//end of class

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

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 article has been dead for over six months. Start a new discussion instead.