代码之家  ›  专栏  ›  技术社区  ›  whitebrow

带有非压缩字符串的Java compact string equalsIgnoreCase计算结果为false

  •  1
  • whitebrow  · 技术社区  · 7 年前

    解析a时 .csv 迭代文件的列标题,看看其中一个是否等于(忽略大小写)comparand id

    String comparand = "id";
    for (String header : headerMap.keySet()) {
       if (header.equalsIgnoreCase(comparand)) {
          recordMap.put("_id", csvRecord.get(header));
       } else {
          recordMap.put(header, csvRecord.get(header));
       }
    }
    

    文件是使用 UTF-8 字符集:

    Reader reader = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
    

    我使用的CSV解析器库是 Apache Commons CSV :

    CSVParser csvParser = CSVFormat.DEFAULT
       .withDelimiter(delimiter)
       .withFirstRecordAsHeader()
       .withIgnoreEmptyLines()
       .parse(reader);
    
    Map<String, Integer> headerMap = csvParser.getHeaderMap();
    

    不知怎么的上面 equalsIgnoreCase() 计算结果为 false 两个字符串都有 身份证件 .

    header 值是非紧凑字符串(UTF-16),而 comparand compact string (ASCII码):

    Non-compact string vs. compact string

    这是默认行为还是错误?我怎么做 equalsIgnoreCase 评估到 true

    1 回复  |  直到 7 年前
        1
  •  4
  •   Karol Dowbecki    6 年前

    你的 header 值以 UTF-16 BOM FFFE . 读取时剥离BOM 在比较之前 comparand .