jaleel
jaleel

Reputation: 1187

remove special char in java string

i have a string like

String mydate = jan\10 ;

but when i print this string i did n't get currect string. so i want replace the char \ by any other char , like #,@ etc..

how it is possible..

Upvotes: 0

Views: 2143

Answers (4)

Varun Madiath
Varun Madiath

Reputation: 3252

mydate.replaceAll("\\\\","#");

Will replace it. The reason you need four backslashes is that the first argument is a regular expression, which expects backslashes to be escaped, and then java expects the backslashes in strings to be escaped as well, leading to the four backslashes. Alternatively you could just declare your string like

String mydate = "jan\\10" ;

and have it print normally.

Upvotes: 0

Matthew Cox
Matthew Cox

Reputation: 13672

String myDate = @"jan\10";
String newDate = myDate.replace('\\', '#');

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240908

String str = "hello\\world";
System.out.println(str.replaceAll("\\\\", "@"));

output:

hello@world

Upvotes: 0

Sergey Vedernikov
Sergey Vedernikov

Reputation: 7754

You must to shield slash: String mydate = "jan\\10" ;

If you want to replace this char:

mydate = mydate.replace("\\", "#");//result is jan#10

Upvotes: 1

Related Questions