Remove the last characters of the Java String variable

Explicit String variable whose value

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

I want to delete the last four characters, i.e. .null . Which method can I use for separation.

+47
java string
Feb 03 '12 at 7:40
source share
6 answers

I think you want to delete the last five characters ('.', 'N', 'u', 'l', 'l'):

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

Note how you need to use the return value. Strings are immutable, so substring (and other methods) do not change the existing string - they return a link to a new string with the corresponding data.

Or be a little safer:

 if (path.endsWith(".null")) { path = path.substring(0, path.length() - 5); } 

However, I will try to solve the problem above. I assume that you only have ".null", because some other code does something like this:

 path = name + "." + extension; 

where extension is null. I would prefer that you never get bad data instead.

(As noted in the interrogative comment, you really need to look at the String API . This is one of the most commonly used classes in Java, so there is no excuse for not being familiar with it.)

+115
Feb 03 2018-12-12T00:
source share
— -
 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" 
+25
Oct 08 '13 at 22:20
source share
 path = path.substring(0, path.length() - 5); 
+6
03 . 2018-12-12T00:
source share

I am surprised to see that all the other answers (as of September 8, 2013) include either counting the number of characters in the substring ".null" , or throw 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 a substring is not found, nothing happens because there is nothing to trim. You will not get a StringIndexOutOfBoundsException . In addition, you do not need to read characters in the substring.

+4
Sep 08 '13 at 16:24
source share

If you want to delete the last 5 characters, you can use:

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

(may contain one error;))

If you like to delete the variable string:

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

(may also contain one error;))

+3
Feb 03 2018-12-12T00:
source share

Another way:

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

By the way, this is the Scala code. Brackets may be required to work in Java.

+1
Aug 05 '15 at 11:27
source share



All Articles