IAmYourFaja
IAmYourFaja

Reputation: 56914

Replace a string by character code instead of regex?

Does Java (or any other 3rd party lib) provide an API for replacing characters based on character code (within a known Charset of course) rather than a regex? For instance, to replace double quotes with single quotes in a given string, one might use:

String noDoubles = containsDoubles.replace("\"", "'");

However the UTF-8 character code for a double quote is U+0022. So is there anything that could search for instances of U+0022 characters and replace them with single quotes?

Also, not just asking about double/single quotes here, I'm talking about the character code lookup and replacement with any 2 characters.

Upvotes: 1

Views: 4203

Answers (3)

joescii
joescii

Reputation: 6533

You can also use a regex still. From the Javadoc:

\xhh The character with hexadecimal value 0xhh

\uhhhh The character with hexadecimal value 0xhhhh

Hence you could write this:

String noDoubles = containsDoubles.replace("\\u0022", "'");

Upvotes: -1

Óscar López
Óscar López

Reputation: 236004

Simply use the unicode literal:

// I'm using an unicode literal for "
String noDoubles = containsDoubles.replace('\u0022', '\'');

The above will work for any character, as long as you know its corresponding code.

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213233

Use the overloaded version - String#replace(char, char) which takes characters. So, you can use it like this:

String str = "aa \" bb \"";
str = str.replace('\u0022', '\'');
System.out.println(str);  // aa ' bb '

Upvotes: 5

Related Questions