Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last chars of the Java String variable

Tags:

java

string

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.

like image 540
Sangram Anand Avatar asked Feb 03 '12 07:02

Sangram Anand


People also ask

How do you get rid of the last char in a string Java?

The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.

How do I remove the last 3 characters of a string?

slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.

How do you remove a character from a string in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.


1 Answers

I think you want to remove 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) don't change the existing string - they return a reference to a new string with the appropriate data.

Or to be a bit safer:

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

However, I would try to tackle the problem higher up. My guess is that you've only got the ".null" because some other code is doing something like this:

path = name + "." + extension; 

where extension is null. I would conditionalise that instead, so you never get the bad data in the first place.

(As noted in a question comment, you really should look through the String API. It's one of the most commonly-used classes in Java, so there's no excuse for not being familiar with it.)

like image 145
Jon Skeet Avatar answered Sep 23 '22 08:09

Jon Skeet