代码之家  ›  专栏  ›  技术社区  ›  Vivin Paliath

如何在Java中执行编码无关的字符串比较?

  •  4
  • Vivin Paliath  · 技术社区  · 14 年前

    我在比较字符串时遇到了一个奇怪的问题。我发送一个字符串到我的服务器(作为字节使用 getBytes() )从客户那里。我已经通过使用 -Dfile.encoding=UTF-8 .

    我在试着做手术时注意到了这个问题 valueOf 在从客户机接收的字符串上,将其转换为枚举。当我打印字符串时,它们看起来 确切地 compareTo ,我得到一个非零的数字 equals 退货 false .

    这就是我得到的:

    Waiting for connections on port 9090
    Connected to client: 127.0.0.1
    received command: GetAllItems
    The value is |GetAllItems| (from client)
    The value is |GetAllItems| (from enum)
    equals: false
    

    我做错什么了?

    下面是我如何从流中重建字符串。也许这就是我做错的地方?

    byte[] commandBytes = new byte[1024];
    in.read(commandBytes); //in is a BufferedInputReader
    String command = new String(commandBytes);
    
    3 回复  |  直到 14 年前
        1
  •  4
  •   Tim Yates    14 年前

    我的猜测是,由于缓冲区大于字符串,因此在重新设置的字符串中会添加空值。在Java中,在字符串中嵌入null是合法的(与C和company不同),尽管Java处理它们的方式与标准UTF-8不同。

    尝试记录读取的长度,并将该长度传递给字符串构造函数:

    int bytesRead = in.read(commandBytes);
    String command = new String(commandBytes, 0, bytesRead);
    
        2
  •  3
  •   Rob Di Marco    14 年前

    byte[] commandBytes = new byte[1024];
    int length = in.read(commandBytes); //in is a BufferedInputReader
    String command = new String(commandBytes, 0, length);
    
        3
  •  2
  •   oers Alfian Busyro    13 年前

    使用 java.text.Collator 比较字符串。