What is the right way in Java to check a string for the symbol ®?

I want to check if a string contains the restricted symbol (®). As of now, I’m doing it like this:

if(mystr.contains("®"))
{
    //do stuff
}

This seems to work, but I really don’t think using the restricted symbol in actual code is the best approach here. What is an alternative way to check if a string contains the restricted symbol?

Answer

With the right encoding there shouldn’t be a problem with your code. But you can also escape it to avoid issues due to the encoding used by the editor:

if(mystr.contains("u00AE"))

During the lexical translation phase, the compiler will translate to the Unicode character.

See also Why does Java permit escaped unicode characters in the source code?

Leave a Reply

Your email address will not be published. Required fields are marked *