0

I want to remove last occurrence of "\" this special character from my string. I tried it with string functions like

String word = str.substring(str.lastIndexOf("\"));

But every time I am getting an error which is asking to put an extra quote. Meanwhile I found out ("\"") is used to pass " this special character. How do I proceed?

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
Yashu
  • 49
  • 12

2 Answers2

10

You need to use

String word = str.substring(str.lastIndexOf("\\"));

the \ character inside a string is escaping special characters (",',\ and so forth). So using a \ before them would make it literal, which means java treats what comes after it as if it's a regular character.

You can test to see what

System.out.println("\\"); 

would print. It would print \.

So:

System.out.println("\" "); //would print one like this: "
System.out.println("\' "); //would print one like this: '

and so on.

ItamarG3
  • 4,092
  • 6
  • 31
  • 44
1

\ is an escape character. If you are using "\", its like escaping " character. Java understands it as " \" (quote missing). Hence the error to close the quote appears.

To resolve it you need to escape the \ character.

String word = str.substring(str.lastIndexOf("\\"));
Abhishek
  • 91
  • 9