[java] Remove the last chars of the Java String variable

A java String variable whose value is

String path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"

I want to remove the last four characters i.e., .null. Which method I can use in order to split.

This question is related to java string

The answer is


Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.


If you like to remove last 5 characters, you can use:

path.substring(0,path.length() - 5)

( could contain off by one error ;) )

If you like to remove some variable string:

path.substring(0,path.lastIndexOf('yoursubstringtoremove));

(could also contain off by one error ;) )


I am surprised to see that all the other answers (as of Sep 8, 2013) either involve counting the number of characters in the substring ".null" or throw a StringIndexOutOfBoundsException if the substring is not found. Or both :(

I suggest the following:

public class Main {

    public static void main(String[] args) {

        String path = "file.txt";
        String extension = ".doc";

        int position = path.lastIndexOf(extension);

        if (position!=-1)
            path = path.substring(0, position);
        else
            System.out.println("Extension: "+extension+" not found");

        System.out.println("Result: "+path);
    }

}

If the substring is not found, nothing happens, as there is nothing to cut off. You won't get the StringIndexOutOfBoundsException. Also, you don't have to count the characters yourself in the substring.


import org.apache.commons.lang3.StringUtils;

// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf.null"
StringUtils.removeEnd(path, ".null");
// path = "http://cdn.gs.com/new/downloads/Q22010MVR_PressRelease.pdf"

path = path.substring(0, path.length() - 5);