我正在自学如何使用 Java 进行编码,并使用在 Internet 上找到的练习来练习所学内容。
我现在正在做一个问题,要求我比较两个字符串(来自用户的输入)并检查这两个字符串是否包含相同的字母。
例子:
areAnagrams("asd","dsa") -> true
areAnagrams("Debit Card","Bad Credit")=> true
明白了吗?
我知道 == 仅在它们都引用同一个对象时才检查。 我以为
public int compareTo(String otherString)
应该完成这项工作。 但它不起作用 =\
到目前为止我所做的是:
public static boolean areAnagrams(String a, String b)
{
int x=0;
a.trim();
b.trim();
x=a.compareTo(b);
System.out.println(x);
return x==0 ? true:false;
}
public static void main(String[] args)
{
Scanner temp= new Scanner(System.in);
Scanner temp2= new Scanner(System.in);
String a= temp.next();
String b= temp2.next();
System.out.println(areAnagrams(a,b));
}
}
但它不起作用。我认为有一个命令应该比较值,但我无法在网上找到它。
会感谢你的帮助
谢谢!
最佳答案
像这样尝试使用 Arrays
怎么样:-
char[] w1= firstWord.trim().toUpperCase().replaceAll("[\\s]", "").toCharArray();
char[] w2= secondWord.trim().toUpperCase().replaceAll("[\\s]", "").toCharArray();
Arrays.sort(w1);
Arrays.sort(w2);
return Arrays.equals(w1, w2);
关于java - 如何比较两个字符串的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18945531/