Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the last index of "\" in a string in java

Tags:

java

string

Can anyone help me find the LastIndexOf '\' in a string in java? I wrote the code as:

int i = app.lastIndexOf('\');

app is my string, but there is a error as "Invalid character constant". I tried using double quotes but still no use. Can anyone help me on this?

like image 949
Nishant Nair Avatar asked Jan 16 '12 15:01

Nishant Nair


People also ask

How do I find the last index of a string?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

How do you find the index of a string in Java?

Java String indexOf() Method The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

What is the difference between indexOf and lastIndexOf in Java?

indexOf() method returns the position of the first occurrence of a specified value in a string. string. lastIndexOf() method returns the position of the last occurrence of a specified value in a string.


2 Answers

The \ character is used to escape other characters, in order to print special characters.

For example, '\n' is the "newline" character, '\t' is the "tab" character, '\'' is the literal ', etc.

In order to use a \ in a string, you have to escape it: \\.

Use app.lastIndexOf('\\');

like image 193
Patrick Perini Avatar answered Sep 22 '22 13:09

Patrick Perini


You have to escape \ as \\ in java Strings.

like image 23
soulcheck Avatar answered Sep 23 '22 13:09

soulcheck