Menu

Showing posts with label Substring in Java. Show all posts
Showing posts with label Substring in Java. Show all posts

How to get the last path segment of an URL using Java

With any programming language, we come at some point where we need the last segment of the URL to manage and moderate the request and response. Hence with this sample Java program, we will see how we can get the last segment of the URL or URI after a slash (/).

public class JavaSubStringSample {

	public static void main(String[] args) {
		String path = "http://localhost/customize";
		String finalName = path.substring(path. lastIndexOf('/'));
		System.out.println(finalName);
	}
}


The above program will return the last segment of a given URL from the path variable. i.e. /customize. You may also remove the special charecter slash by adding +1 after lastIndexOf method in substring method.


Java LastIndexOf() - rashid jorvee
Screenshot of result