Delete the last two characters of the String

172,292

Solution 1

Subtract -2 or -3 basis of removing last space also.

 public static void main(String[] args) {
        String s = "apple car 05";
        System.out.println(s.substring(0, s.length() - 2));
    }

Output

apple car

Solution 2

Use String.substring(beginIndex, endIndex)

str.substring(0, str.length() - 2);

The substring begins at the specified beginIndex and extends to the character at index (endIndex - 1)

Solution 3

You may use the following method to remove last n character -

public String removeLast(String s, int n) {
    if (null != s && !s.isEmpty()) {
        s = s.substring(0, s.length()-n);
    }
    return s;
}

Solution 4

You can use substring function:

s.substring(0,s.length() - 2));

With the first 0, you say to substring that it has to start in the first character of your string and with the s.length() - 2 that it has to finish 2 characters before the String ends.

For more information about substring function you can see here:

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Solution 5

It was almost correct just change your last line like:

String stopEnd = stop.substring(0, stop.length() - 1); //replace stopName with stop.

OR

you can replace your last two lines;

String stopEnd =   stopName.substring(0, stopName.length() - 2);
Share:
172,292
TheBook
Author by

TheBook

Updated on July 05, 2022

Comments

  • TheBook
    TheBook almost 2 years

    How can I delete the last two characters 05 of the simple string?

    Simple:

    "apple car 05"
    

    Code

    String[] lineSplitted = line.split(":");
    String stopName = lineSplitted[0];
    String stop =   stopName.substring(0, stopName.length() - 1);
    String stopEnd = stopName.substring(0, stop.length() - 1);
    

    orginal line before splitting ":"

    apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16
    
  • masud.m
    masud.m almost 9 years
    It may not work if we increase the string size. So I think it's better to remove from the last what is seen in other answers.
  • Isuru Gunawardana
    Isuru Gunawardana almost 9 years
    @masud.m updated the answer as you suggested.
  • Sankalp
    Sankalp over 4 years
    Why does Java doesn't want to clean this functionality up? String parsing is extensively used in Orgs of every scale. In Python its as simple as s[:-2]. That's it.
  • Harini Sampath
    Harini Sampath almost 4 years
    should be str.length - 3
  • Vasia Zaretskyi
    Vasia Zaretskyi about 3 years
    @Sankalp, Python is easier to learn, but it is slow and sometimes unpredictable. In Java you type more code, but you get fast and reliable result.