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.
Use pop_back() Function to Remove Last Character From the String in C++ The pop_back() is a built-in function in C++ STL that removes the last element from a string. It simply deletes the last element and adjusts the length of the string accordingly.
To remove the last word from a string, get the index of the last space in the string, using the lastIndexOf() method. Then use the substring() method to get a portion of the string with the last word removed.
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;
}
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);
}
}
Since we're on a subject, one can use regular expressions too
"aaabcd".replaceFirst(".$",""); //=> aaabc
The described problem and proposed solutions sometimes relate to removing separators. If this is your case, then have a look at Apache Commons StringUtils, it has a method called removeEnd which is very elegant.
Example:
StringUtils.removeEnd("string 1|string 2|string 3|", "|");
Would result in: "string 1|string 2|string 3"
public String removeLastChar(String s) {
if (s == null || s.length() == 0) {
return s;
}
return s.substring(0, s.length()-1);
}
Don't try to reinvent the wheel, while others have already written libraries to perform string manipulation:
org.apache.commons.lang3.StringUtils.chop()
Use this:
if(string.endsWith("x")) {
string= string.substring(0, string.length() - 1);
}
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