Remove the Last Character of a String in Java
In Java programming, we always need to deal with String operations. Remove the Last Character of a String is a more frequently used operation like others. There are different ways to Remove the Last Character of a String in Java.
1). Using String.substring()
2). Using StringBuffer
3). Using StringUtils.chop() Method
4). Using Regular Expression
1). Using String.substring()
public String method(String str,char ch) {
if (str != null && str.length() > 0 && str.charAt(str.length() - 1) == ch) {
str = str.substring(0, str.length() - 1);
}
return str;
}
2). Using StringBuffer
The StringBuffer class provides a method deleteCharAt(). The method deletes a character from the specified position. We use the method to remove a character from a string in Java.
It accepts a parameter index of type int. The index is the position of a character we want to delete. It returns this object.
String string = "hello world!!!!";
StringBuffer sb= new StringBuffer(string);
sb.deleteCharAt(sb.length()-1);
System.out.println(sb);
3). Using StringUtils.chop() Method
Maven dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
The StringUtils class provides a chop() method to remove the last character from a string. The method parses a parameter of type String. It also accepts null, as a parameter.
It returns the string after removing the last character. It returns a null when we input a null string.
import org.apache.commons.lang3.StringUtils;'
public class RemoveChacterStringUtils {
public static void main(String[] args) {
String string = "Hello World";
string = StringUtils.chop(string);
System.out.println(string);
}
}
4). Using Regular Expression
We can use the regular expression to remove the last character from the string. The String class provides the replaceAll() method that parses two parameters regex and replacement of type String. The method replaces the string with the specified match.
regex: It is the expression with which the string is to match. replacement: It is the replacement string or substitute string for each match.
"hello".replaceAll(".$", "");
But this operation is not a thread-safe.
Also, replaceAll() and regex expression combination is done as follows.
public static String removeLastCharRegex(String s) {
return (s == null) ? null : s.replaceAll(".$", "");
}
In this article, we have seen Remove the Last Character of a String in Java.
0 Comments
Post a Comment