Java – Remove last character in string
To remove the last character in given string in Java, you can use the String.substring() method. Call substring() method on the given string, and pass the start index of 0 and end index of string length – 1 as argument. The method returns a substring string from starting of the string to last but one character of the string, thus removing the last character.
If str is given string, then the expression to get a resulting string with the last character removed from the string is
str.substring(0, str.length()-1)
1. Remove last character from string using String.substring() in Java
In this example, we take a string "Apple"
in str and remove the last character in the string using String.substring() method.
Java Program
public class Main {
public static void main(String[] args) {
String str = "Apple";
// Remove last character
String resultString = str.substring(0, str.length()-1);
System.out.println(resultString);
}
}
Output
Appl
Conclusion
In this Java String tutorial, we have seen how to remove the last character in a given string in Java using String.substring() method, with examples.