java 我如何比较java中的字符串和字符数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14264795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i compare a string and a char array in java?
提问by Laura Canter
In my program I'm trying to compare my char array asterixA[]
to string (word) in an if loop like:
在我的程序中,我试图asterixA[]
在 if 循环中将我的字符数组与字符串(单词)进行比较,例如:
if (word.equals(asterixA))
but its giving me an error. Is there any other way i can compare them?
但它给了我一个错误。有没有其他方法可以比较它们?
回答by PermGenError
you have to convert the character array into String or String to char array and then do the comparision.
您必须将字符数组转换为 String 或 String 到 char 数组,然后进行比较。
if (word.equals(new String(asterixA)))
or
或者
if(Arrays.equals(word.toCharArray(), asterixA))
BTW. if is a conditional statement not a loop
顺便提一句。if 是条件语句而不是循环
回答by Fritz
You seem to be taking the "A String is an array of chars" line too literal. String
's equals
method states that
您似乎将“字符串是字符数组”这一行过于字面化。String
的equals
方法指出
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.
在这种情况下, aString
不是 a char[]
,但 Java 提供了从一个到另一个的机制,可以通过使用 进行String -> char[]
转换,String#toCharArray()
或者char[] -> String
通过将char[]
作为参数传递给String
的构造函数来进行转换。
This way you can compare both objects after either turning your String
into a char[]
or vice-versa.
通过这种方式,您可以在将您的对象String
变成 achar[]
或反之亦然后比较两个对象。
回答by hmatar
do as follows: if(word.equals(new String((asterixA))
做如下: if(word.equals(new String((asterixA))
回答by assylias
You can compare the arrays:
您可以比较数组:
if (Arrays.equals(asterixA, word.toCharArray()) {}