How to remove specific characters at the end in Java
You can remove specific characters from the end using the substring method of the String class in Java. Here is an example code:
public class Main {
public static void main(String[] args) {
String str = "Hello World!";
char charToRemove = '!';
String result = removeTrailingChar(str, charToRemove);
System.out.println(result);
}
public static String removeTrailingChar(String str, char charToRemove) {
int length = str.length();
int endIndex = length - 1;
while (endIndex >= 0 && str.charAt(endIndex) == charToRemove) {
endIndex--;
}
return str.substring(0, endIndex + 1);
}
}
In the example above, we have defined a method called removeTrailingChar, which takes a string and the character to be removed as parameters. In the method, we traverse from the end of the string until we find the first character that is not equal to the one to be removed. Then, we use the substring method to create a new substring from the start of the string to the found index (including that index), and return it.
The output result is “Hello World” without the exclamation mark at the end.