Yashpal Singla
Yashpal Singla

Reputation: 1994

How can i replace { inside string in java

Can anybody help me in replacing '{' inside string in java

For e.g.

String str = "abc{ad}";
str = str.replace("{","(");

But this seems to be not possible.

Upvotes: 3

Views: 204

Answers (3)

amit
amit

Reputation: 178481

String#replace(char,char) does it and fits for one character. All you have to do is switch your replace() invokation to:

str = str.replace('{','(');
 //               ^ ^ ^ ^
 //             not the ' instead of "

However, String in java is immutable so you cannot change it1, you can only generate a new string object with these properties.


(1) not easily anyway, can be done with reflection API, but it is unadvised.

Upvotes: 5

NPKR
NPKR

Reputation: 5506

This will work for

String strAll = "abc{ad}";
strAll = strAll.replaceAll("\\{","(");

Upvotes: 0

PermGenError
PermGenError

Reputation: 46428

{ and ( are meteacharacters in java, you should escape them with backslash . and String.replace doesn't use regex, use [String.replaceAll][1] or String.replaceFirst instead

str = str.replaceAll("\\{","\\(");

Upvotes: 2

Related Questions