zahir
zahir

Reputation: 51

Replace special characters in string in Java

How can I replace the string in Java?

E.g.,

String a = "adf�sdf";

How can I replace and avoid special characters?

Upvotes: 5

Views: 22870

Answers (4)

ablaeul
ablaeul

Reputation: 2798

Assuming that you want to remove all special characters, you can use the character class \p{Cntrl}. Then you only need to use the following code:

stringWithSpecialCharcters.replaceAll("\\p{Cntrl}", replacement);

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074148

You can use Unicode escape sequences (such as \u201c [an opening curly quote]) to "avoid" characters that can't be directly used in your source file encoding (which defaults to the default encoding for your platform, but you can change it with the -encoding parameter to javac).

Upvotes: 0

BalusC
BalusC

Reputation: 1108662

You can get rid of all characters outside the printable ASCII range using String#replaceAll() by replacing the pattern [^\\x20-\\x7e] with an empty string:

a = a.replaceAll("[^\\x20-\\x7e]", "");

But this actually doesn't solve your actual problem. It's more a workaround. With the given information it's hard to nail down the root cause of this problem, but reading either of those articles must help a lot:

Upvotes: 14

Daniel Rikowski
Daniel Rikowski

Reputation: 72504

It is hard to answer the question without knowing more of the context.

In general you might have an encoding problem. See The Absolute Minimum Every Software Developer (...) Must Know About Unicode and Character Sets for an overview about character encodings.

Upvotes: 2

Related Questions