arkhadi
arkhadi

Reputation: 41

Problem with equals Strings in Java

I have two "equal" Strings. When I print both Strings they look exactly the same in the screen. But when I compare the Strings the result is "false" and using .length in both Strings the result is 174 for the first String and 171 for the second. I have deleted all whitespaces and everything to set the Strings in one line.

String 1:
<docxmlns="http://example.com/default"xmlns:x="http://example.com/x"><aa1="1"a2="2">123</a><bxmlns:y="http://example.com/y"a3="&quot;3&quot;"y:a1="1"y:a2="2">cdf</b></doc>

String 2:
<docxmlns="http://example.com/default"xmlns:x="http://example.com/x"><aa1="1"a2="2">123</a><bxmlns:y="http://example.com/y"a3="&quot;3&quot;"y:a1="1"y:a2="2">cdf</b></doc>

String 1 length: 174
String 2 length: 171

I copied both Strings from Netbeans console, as you can see they are equals but they have different lengths.

Thanks.

Upvotes: 0

Views: 4006

Answers (5)

Costi Ciudatu
Costi Ciudatu

Reputation: 38225

Try to print them as characters:

System.out.println( Arrays.toString( yourString.toCharArray() );

This should allow you to see where the non-printable characters (or whatever differs) are, as the output for "abc" will be "[a, b, c]".

Upvotes: 2

Matteo
Matteo

Reputation: 1377

Did you cut & paste the strings from an external source, such as a PDF? Some years ago I had a similar issue, and I discovered that strings copied from PDFs sometimes include some invisible characters (I used Acrobat Reader).

Upvotes: 0

highlycaffeinated
highlycaffeinated

Reputation: 19867

Call getBytes() on both strings and print the results. I'm betting you have an encoding difference.

Upvotes: 2

Marcelo
Marcelo

Reputation: 11308

When you are reading it in your java program maybe the string contains newline characters ("\n\r" in Windows) which can alter the length and equality in both strings.

Upvotes: 3

mark-cs
mark-cs

Reputation: 4707

I have deleted all whitespaces and everything to set the Strings in one line.

White space is important and may be the deciding factor in your equals problem here. As a test to see if it is, strip the white space from both strings then perform an equals check.

Upvotes: 0

Related Questions