Reputation: 6158
I have a String str=p2\7\2010
I want to check and replace if str.contains("\")
then replace it into this("\\\\")
instead of \
. i am unable to do this in Java please give your little effort.
Upvotes: 3
Views: 3688
Reputation: 31192
use String.replace():
if (str.contains("\\")) {
str = str.replace("\\", "\\\\");
}
You can also use String.replaceAll()
, but it uses regular expressions and so is slower in such trivial case.
UPDATE:
Implementation of String.replace()
is based on regular expressions as well, but compiled in Pattern.LITERAL mode.
Upvotes: 4
Reputation: 432
Try this,
String newString = oldString.replace("/", "//");
or try pattern method,
Pattern pattern = Pattern.compile("/");
Matcher matcher = pattern.matcher("abc/xyz");
String output = matcher.replaceAll("//");
Upvotes: 0
Reputation: 2815
str.contains("\"")
matches string that have a " in them.
What you probably want is str.replaceAll("\\", "\\\\")
Additionally; for checking if it contains a \ you'd need str.contains("\\")
, since the \ is a special character it has to be escaped.
Upvotes: 0