Testing out someone elses code, I noticed a few JSP pages printing funky non-ASCII characters. Taking a dip into the source I found this tidbit:
// remove any periods from first name e.g. Mr. John --> Mr John
firstName = firstName.trim().replace('.','\0');
Does replacing a character in a String with a null character even work in Java? I know that '\0'
will terminate a C-string. Would this be the culprit to the funky characters?
Should be probably changed to
No.
Quite likely.
That depends on how you define what is working. Does it replace all occurrences of the target character with
'\0'
? Absolutely!Everything seems to work fine to me!
indexOf
can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!
It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):
Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.
That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.
Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the
replace(CharSequence, CharSequence)
overload.The
replaceAll
solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.This does cause "funky characters":
produces:
in my Eclipse console, where the [] is shown as a square box. As others have posted, use
String.replace()
.I think it should be the case. To erase the character, you should use
replace(".", "")
instead.