I am trying to trim StringBuilder
from right side, something like this :
private StringBuilder rtrim(StringBuilder str, Character trimStr) {
if (str.charAt(str.length() - 1) == trimStr) {
return str.deleteCharAt(str.length() - 1);
}
return str;
}
The above function works fine with character as trimStr, but I want to pass trimStr as string. Any library for the same(similar to StringUtils)?
You can use replaceAll or just replaceFirst with regex like so :
String str = " some string ";
str = str.replaceAll("\\s*$", "");//output is " some string"
Edit
If you are using StringBuilder you can use :
private static StringBuilder rtrim(StringBuilder str, String trimStr) {
return new StringBuilder(
str.toString().replaceFirst("(" + Pattern.quote(trimStr) + ")+$", "")
);
}
Some inputs and outputs
" some string " + " " ==> " some string"
" some stringaaa" + "a" ==> " some string"
" some stringabab" + "ab" ==> " some string"
For left trim you can just change your regex to be str.toString().replaceFirst("^(" + Pattern.quote(trimStr) + ")+", "")
private static StringBuilder rtrim(StringBuilder str, String trimStr) {
return new StringBuilder(
str.toString().replaceFirst("^(" + Pattern.quote(trimStr) + ")+", "")
);
}
Another Solution without regex
public StringBuilder rTrim(StringBuilder str, String trimStr) {
if (str != null && trimStr != null) {
int trimLen = trimStr.length();
int strLen = str.length();
if (strLen != 0 && trimLen != 0) {
while (strLen != 0 && str.substring(strLen - trimLen, strLen).equals(trimStr)) {
str = str.delete(strLen - trimLen, strLen);
strLen = str.length();
}
}
}
return str;
}
public StringBuilder lTrim(StringBuilder str, String trimStr) {
if (str != null && trimStr != null) {
int len = trimStr.length();
if (str.length() != 0 && len != 0) {
while (str.length() != 0 && str.substring(0, len).equals(trimStr)) {
str = str.delete(0, len);
}
}
}
return str;
}