Yashu Yashu -4 years ago 62
Java Question

Str.lastIndexOf("\") giving an error

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?

Answer Source

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


would print. It would print \.


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

and so on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download