3

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.

3
  • try str = str.replace("\{","("); Commented Dec 26, 2012 at 9:53
  • replace replaces characters not Strings. Commented Dec 26, 2012 at 10:02
  • What JDK version do you have? Commented Dec 26, 2012 at 10:09

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I would remove the note about reflection. It just adds noise, IMO, and could make the reader think that it would be a wise thing to modify a string using reflection.
@JBNizet: I see your point, but claiming "it cannot be done" is wrong without this clarification, I subbed it to generate less noise, I would also appritiate any edit that one may think explains it is should be avoided better.
2

{ 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("\\{","\\(");

Comments

0

This will work for

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.