Delete the last two characters of the String

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
197797 次浏览

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

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)

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

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);

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;
}

An alternative solution would be to use some sort of regex:

for example:

    String s = "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";
String results=  s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
System.out.println(results); // output 9
System.out.println(results.length());// output "apple car"

You may also try the following code with exception handling. Here you have a method removeLast(String s, int n) (it is actually an modified version of masud.m's answer). You have to provide the String s and how many char you want to remove from the last to this removeLast(String s, int n) function. If the number of chars have to remove from the last is greater than the given String length then it throws a StringIndexOutOfBoundException with a custom message -

public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{


int strLength = s.length();


if(n>strLength){
throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
}


else if(null!=s && !s.isEmpty()){


s = s.substring(0, s.length()-n);
}


return s;


}