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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With