Search code examples
javatemperaturereplaceall

How to remove the degrees celsius symbol from a string (java)


I've been trying to remove the degree Celsius symbol from the following string for a few hours now. I've looked at prior posts and I see that /u2103 is the unicode representation for it. Despite trying to remove that string, I've still had no luck. Here's what I have now:

String temp = "Technology=Li-poly;Temperature=23.0 <degree symbol>C;Voltage=3835";
StringBuilder filtered = new StringBuilder(temp.length()); 
    for (int i = 0; i < temp.length(); i++) {
char test = temp.charAt(i);
if (test >= 0x20 && test <= 0x7e) {
    filtered.append(test);
}
}

temp = filtered.toString();

temp.replaceAll(" ", "%20");

The resulting string looks like this: Technology=Li-poly;Temperature=23.0 C;

I've also tried

temp.replaceAll("\\u2103", "");
temp.replaceChar((char)0x2103, ' ');

But none of this works.

My current problem is that the function to filter the string leaves a blank space but the call to replaceAll(" ", "%20") doesn't seem to recognize that particular space. ReplaceAll will replace other spaces with %20.


Solution

  • This is one problem:

    temp.replaceAll(" ", "%20");
    

    You're calling replaceAll but never using the result. Strings are immutable - any method which looks like it's changing the content is actually returning the different string as a result. You want:

    temp = temp.replaceAll(" ", "%20");
    

    Having said that, it's not clear why you're trying to replace the space at all, nor what's wrong with your resulting string.

    You've got the same problem with your other temp.replaceAll and temp.replaceChar calls.

    Your attempt to replace the character directly would also fail as you're escaping the backslash - you really want:

    temp = temp.replace("\u2103", "");
    

    Note the use of replace instead of replaceAll - the latter uses regular expressions, which there's no need to use at all here.