简体   繁体   English

我如何比较 Java 中的字符串和字符数组?

[英]How can I compare a string and a char array in Java?

In my program I'm trying to compare my char array asterixA[] to a String word in an if condition like:在我的程序中,我试图在 if 条件下将我的 char 数组asterixA[]与字符串word进行比较,例如:

if (word.equals(asterixA))

but it's giving me an error.但它给了我一个错误。 Is there any other way I can compare them?还有其他方法可以比较它们吗?

you have to convert the character array into String or String to char array and then do the comparision.您必须将字符数组转换为字符串或将字符串转换为字符数组,然后进行比较。

if (word.equals(new String(asterixA)))

or要么

if(Arrays.equals(word.toCharArray(), asterixA))

BTW.顺便提一句。 if is a conditional statement not a loop if 是条件语句不是循环

You seem to be taking the "A String is an array of chars" line too literal.您似乎把“A String is an array of chars”这一行看得太直白了。 String 's equals method states that Stringequals方法指出

Compares this string to the specified object.将此字符串与指定对象进行比较。 The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.当且仅当参数不为 null 并且是表示与此对象相同的字符序列的 String 对象时,结果才为真。

It all depends of the circumstances, but generally you compare two objects of the same type or two objects belonging to the same hierarchy (sharing a common superclass).这完全取决于具体情况,但通常您比较两个相同类型的对象或属于同一层次结构(共享一个公共超类)的两个对象。

In this case a String is not a char[] , but Java provides mechanisms to go from one to the other, either by doing a String -> char[] transformation with String#toCharArray() or a char[] -> String transformation by passing the char[] as a parameter to String 's constructor.在这种情况下, String不是char[] ,但 Java 提供了从一个到另一个的机制,通过使用String#toCharArray()进行String -> char[]转换或char[] -> String转换通过将char[]作为参数传递给String的构造函数。

This way you can compare both objects after either turning your String into a char[] or vice-versa.通过这种方式,您可以在将String转换为char[]后比较两个对象,反之亦然。

do as follows: if (word.equals(new String(asterixA))) {... }做如下: if (word.equals(new String(asterixA))) {... }

You can compare the arrays:您可以比较数组:

if (Arrays.equals(asterixA, word.toCharArray()) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM