简体   繁体   English

Java字符串比较

[英]Java String comparison

I have the following statement in my java code 我的java代码中有以下语句

System.out.println(cName+" "+pName+" "+cName.equals(pName));

Output is 输出是

???????????????? ???????????????? false

The equals should return true right as the two strings have equal number of '?'. equals应该返回true,因为两个字符串具有相同数量的'?'。 But I am getting false 但我变得虚假

Those 2 String s might be equal in their "printed" form on your console, but their content is certainly not equal as proved by the return value of the String.equals() . 这两个String在你的控制台上的“打印”形式可能是相同的,但它们的内容肯定不相同,这是由String.equals()的返回值证明的。

They most likely contain characters which your console cannot display, therefore your console displays '?' 它们很可能包含控制台无法显示的字符,因此控制台显示'?' characters for the "undisplayable" characters. “不可显示”字符的字符。

Another possibility could be they contain characters which when printed on the console have no visual appearance. 另一种可能性是它们包含在控制台上打印时没有视觉外观的字符。 Such characters may be the zero character ( '\\0' ) and control characters (whose code is less than 32) but this depends on the console how and what it displays. 这些字符可能是零字符( '\\0' )和控制字符(其代码小于32),但这取决于控制台的显示方式和内容。

Note: Even if you open the file where these String s are stored or initialized and you see the same question marks, it is still possible that your editor is also not able to display the characters and the editor also displays question marks ( '?' ) for undisplayable characters or for the characters with no visual appearance. 注意:即使您打开存储或初始化这些String的文件并且您看到相同的问号,您的编辑器仍然无法显示字符,编辑器也会显示问号( '?' )对于不可显示的字符或没有视觉外观的字符。

How to show the difference? 如何显示差异?

Iterate over the characters of the strings, and print them as int numbers where you will see the difference: 迭代字符串的字符,并将它们打印为int数字,您将看到差异:

String s = "Test";
for (int i = 0; i < s.length(); i++)
    System.out.println((int) s.charAt(i));

Now if you see the same numbers printed, then yes, you can be sure they are the same, but then String.equals() would return true . 现在如果你看到相同的数字打印出来,那么是的,你可以确定它们是相同的,但是String.equals()会返回true

Might be because of whitespace it is coming false 可能是因为空白,它会变得false

check for this : 检查一下:

System.out.println(cName+" "+pName+" "+(cName.trim()).equals(pName.trim()));

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

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