刚刚完成了最近的作业,但我知道它可能会更有效率。它从命令行读取两个单词,忽略空格和标点符号,并确定它们是否是字谜。我所拥有的如下;据我所知,它功能齐全。
/**
* Find out if a string is an anagram of another string
*
*/
import java.util.Arrays;
public class Anagram
{
public static void main(String[] args)
{
if (args.length != 2)
System.out.println("You did not enter two words!");
else
printWords(args[0], args[1]);
}
// method to determine whether two strings have the same chars
public static boolean areAnagrams(String wordOne, String wordTwo)
{
// new strings for letters only
String ltrsOnlyOne = lettersOnly(wordOne);
String ltrsOnlyTwo = lettersOnly(wordTwo);
// convert strings to lowercase char arrays
char[] first = ltrsOnlyOne.toLowerCase().toCharArray();
char[] second = ltrsOnlyTwo.toLowerCase().toCharArray();
// sort char arrays using sort method
Arrays.sort(first);
Arrays.sort(second);
if (Arrays.equals(first, second))
return true;
else
return false;
}
public static String lettersOnly(String word)
{
int length = word.length();
StringBuilder end = new StringBuilder(length);
char x;
for (int i = (length - 1); i >= 0; i--) {
x = word.charAt(i);
if (Character.isLetter(x)) {
end.append(x);
}
}
return end.toString();
}
public static void printWords(String wordOne, String wordTwo)
{
boolean b = areAnagrams(wordOne, wordTwo);
if (b == true) {
System.out.println(wordOne + " is an anagram of "+ wordTwo);
}
if (b == false) {
System.out.println(wordOne + " is not an anagram of "+ wordTwo);
}
}
}