Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I\'m trying to write a code to check if two strings are anagrams. i have

ID: 3635338 • Letter: H

Question

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

Explanation / Answer

Just need to clean out any spaces and put all letters into the same case. You can accomplish this without modifying any of the rest of your code or the strings at the end by making copies of them and then feeding those "cleaned" strings into your anagram matcher. Replace your anagram function call with these lines: String string1Clean = string1.toLowerCase(); string1Clean = string1Clean.replaceAll(" ", ""); String string2Clean = string1.toLowerCase(); string2Clean = string2Clean.replaceAll(" ", ""); boolean value = anagram(string1Clean,string2Clean);

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote