Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove escape char ' \' from string in java

Tags:

java

I have to remove \ from the string.

My String is "SEPIMOCO EUROPE\119"

I tried replace, indexOf, Pattern but I am not able to remove this \ from this string

String strconst="SEPIMOCO EUROPE\119";
System.out.println(strconst.replace("\\", " ")); // Gives SEPIMOCO EUROPE 9
System.out.println(strconst.replace("\\\\", " ")); // Gives SEPIMOCO EUROPE 9
System.out.println(strconst.indexOf("\\",0));  //Gives -1

Any solutions for this ?

like image 748
neel.1708 Avatar asked Dec 05 '22 14:12

neel.1708


2 Answers

Your string doesn't actually contain a backslash. This part: "\11" is treated as an octal escape sequence (so it's really a tab - U+0009). If you really want a backslash, you need:

String strconst="SEPIMOCO EUROPE\\119";

It's not really clear where you're getting your input data from or what you're trying to achieve, but that explains everything you're seeing at the moment.

like image 125
Jon Skeet Avatar answered Dec 07 '22 03:12

Jon Skeet


You have to distinguish between the string literal, i.e. the thing you write in your source code, enclosed with double quotes, and the string value it represents. When turning the former into the latter, escape sequences are interpreted, causing a difference between these two.

Stripping from string literals

\11 in the literal represents the character with octal value 11, i.e. a tab character, in the actual string value. \11 is equivalent to \t.

There is no way to reliably obtain the escaped version of a string literal. In other words, you cannot know whether the source code contained \11 or \t, because that information isn't present in the class file any more. Therefore, if you wanted to “strip backslashes” from the sequence, you wouldn't know whether 11 or t was the correct replacement.

For this reason, you should try to fix the string literals, either to not include the backslashes if you don't want them at all, or to contain proper backslashes, by escaping them in the literal as well. \\ in a string literal gives a single \ in the string it expresses.

Runtime strings

As you comments to other answers indicate that you're actually receiving this string at runtime, I would expect the string to contain a real backslash instead of a tab character. Unless you employ some fancy input method which parses escape sequences, you will still have the raw backslash. In order to simulate that situation in testing code, you should include a real backslash in your string, i.e. a double backslash \\ in your string literal.

When you have a real backslash in your string, strconst.replace("\\", " ") should do what you want it to do:

String strconst="SEPIMOCO EUROPE\\119";
System.out.println(strconst.replace("\\", " ")); // Gives SEPIMOCO EUROPE 119
like image 24
MvG Avatar answered Dec 07 '22 03:12

MvG