Reputation: 13
I tried to compare 2 string with the code:
public class MyClass
{
public static void main(String args[])
{
String xhex="31 38 30 2E 32 35 35 2E 32 32 35 2E 31 32 33";
String hex = remspace(xhex).trim().toString();
System.out.println(hex);
String hex1="3138302E3235352E3232352E313233";
System.out.println(hex1);
if(hex.trim().equalsIgnoreCase(hex1.trim()))
//if (hex.equals(hex1))
{
System.out.println("equals");
}else
{
System.out.println("not equals");
}
}
private static String remspace(String data)
{
String xdata = null;
char c='\0';
String hex = data.replace(' ',c);
return hex;
}
}
the result is :
3138302E3235352E3232352E313233
3138302E3235352E3232352E313233
not equals
as we can see the result is identically equals but when i tried to compare the string using equals the result is not equals. any idea why did it considered as not equals ?
Upvotes: 0
Views: 166
Reputation: 6242
This works for me:
public static String removeWhitespaces(String source){
char[] chars = new char[source.length()];
int numberOfNewlines = 0;
for (int i = 0; i<chars.length; i++){
if (source.charAt(i)==' ')
numberOfNewlines++;
else
chars[i-numberOfNewlines]=source.charAt(i);
}
return new String(chars).substring(0, source.length()-numberOfNewlines);
}
Upvotes: 0
Reputation: 16039
They are not identical, the first string has '\0'
in places where the space used to be. They are just displayed on the console as identical because '\0'
is not displayed.
If you want the space to be removed use, change the remspace
method to:
private static String remspace(String data) {
return data.replace(" ", "");
}
Upvotes: 8