Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Getting a substring from a string starting after a particular character

I have a string:

/abc/def/ghfj.doc 

I would like to extract ghfj.doc from this, i.e. the substring after the last /, or first / from right.

Could someone please provide some help?

like image 984
Sunny Avatar asked Jan 14 '13 10:01

Sunny


People also ask

How do you grab a substring after a specified character?

To get the substring after a specific character, call the substring() method, passing it the index after the character's index as a parameter. The substring method will return the part of the string after the specified character. Copied! We used the String.

How do you cut a string after a specific character in Java?

Java – Split a String with Specific Character To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


Video Answer


2 Answers

String example = "/abc/def/ghfj.doc"; System.out.println(example.substring(example.lastIndexOf("/") + 1)); 
like image 104
Sébastien Le Callonnec Avatar answered Sep 21 '22 17:09

Sébastien Le Callonnec


A very simple implementation with String.split():

String path = "/abc/def/ghfj.doc"; // Split path into segments String segments[] = path.split("/"); // Grab the last segment String document = segments[segments.length - 1]; 
like image 25
Veger Avatar answered Sep 18 '22 17:09

Veger