简体   繁体   中英

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.

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 '

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.

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", "'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM