First look at the code below
public static void main(String args[])
{
System.out.println(new Stringtest().test("The system has saved your payment under transaction number \369825655."));
}
private String test(String aa)
{
return aa.substring(58);
}
so logically this method should print 369825665. But it is printing 9825655 because of that backslash. Now I want the whole number. What should I do. I can not change the \ to \\ because the text is coming from a website.
\is an escape character. You need to escape the escape character.For more on escape sequences, see this Oracle document. Essentially the backslash tells the system that the character(s) after it should be interpreted in a special manner (not simply as plain text). When you escape the escape, it gets treated specially as well… as plain text, instead of as an escape character.
It can get confusing sometimes but is intuitive once you learn the core concepts.
EDIT: If you can’t control the format the String comes to you in, you might be out of luck. I’ve been debugging this in Eclipse, and it seems like as soon as you create your String with that, the escape character gets processed and you lose the first two digits of your transaction number. You may need to get your database guys (or whomever formatted this terrible String) to change their implementation for you to do what you need to do. The Eclipse debugger suggests this, at least.
It just so happens that, apparently,
\36processes fine and gets interpreted as another ASCII character that doesn’t show up. But in other cases, this will likely throw an Exception as an invalid escape sequence.In my own testing, it seems that as soon as the String literal is declared/created, the loss of information occurs. So there will be no way to recover it after that to my knowledge.
Debug Screenshot
