How to remove the last character from a string?
Why not just one liner?
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
Full Code
public class Main {
public static void main (String[] args) throws java.lang.Exception {
String s1 = "Remove Last CharacterY";
String s2 = "Remove Last Character2";
System.out.println("After removing s1==" + removeLastChar(s1) + "==");
System.out.println("After removing s2==" + removeLastChar(s2) + "==");
}
public static String removeLastChar(String str) {
return removeLastChars(str, 1);
}
public static String removeLastChars(String str, int chars) {
return str.substring(0, str.length() - chars);
}
}
Demo
replace
will replace all instances of a letter. All you need to do is use substring()
:
public String method(String str) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == 'x') {
str = str.substring(0, str.length() - 1);
}
return str;
}