我尝试将2个字符串与代码进行比较:
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;
}
}
结果是:
3138302E3235352E3232352E313233
3138302E3235352E3232352E313233
not equals
因为我们可以看到结果是相同的,但是当我尝试使用equals比较字符串时,结果不等于。任何想法为什么它被视为不平等?
答案 0 :(得分:8)
它们不相同,第一个字符串在空格所在的位置有'\0'
。它们只是在控制台上显示为相同,因为'\0'
未显示。
如果要删除空格,请将remspace
方法更改为:
private static String remspace(String data) {
return data.replace(" ", "");
}
答案 1 :(得分:0)
这对我有用:
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);
}