subodh
subodh

Reputation: 6158

How to check and replace special character(\) contain in a String in java?

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

Answers (3)

Michał Šrajer
Michał Šrajer

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

Nagarajan
Nagarajan

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

Yhn
Yhn

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

Related Questions