0

I have problem with string comparison in Java. I have 2 nearly similar strings, but they are not equal, because one contains - (44) char and another contains - (8211) char. Can someone help me with case, that this strings are equals. I tried this in code, but it doesn't work:

cellValue.replaceAll("\u0045", "\u8211");
byte[] bytes = cellValue.getBytes(Charset.defaultCharset());
String cellValueUtf8 = new String(bytes, Charset.defaultCharset());
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Petr Kostroun
  • 456
  • 9
  • 27

2 Answers2

0

Strings are constant; their values cannot be changed after they are created. Thus, String#replaceAll returns a new String i.e. this operation doesn't change cellValue. Also, note that String#replaceAll takes a regex as the first parameter.

You need String#replace, which replaces all occurrences of oldChar in the given string with newChar, instead of String#replaceAll.

Replace

cellValue.replaceAll("\u0045", "\u8211");

with

cellValue = cellValue.replace('\u0045', '\u8211');

in order for the changed value to be assigned to cellValue.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
-1

I wrote this method, and it works as I expect:

public static String normalizeDashChar(String toNormalize) {
    char[] bytes = toNormalize.toCharArray();
    for(int i = 0; i < bytes.length; i++) {
        if(bytes[i] == (char)45) {
            bytes[i] = (char)8211;
        }
    }

    return new String(bytes);
}
Petr Kostroun
  • 456
  • 9
  • 27
  • You do not need to reinvent the wheel. `String#replace` will do your job. Check [this answer](https://stackoverflow.com/a/64486404/10819573) for the explanation. Note that I've not downvoted your answer . – Arvind Kumar Avinash Oct 22 '20 at 16:55