In java, we have trim() method to remove trailing and leading spaces.
String s = " dsafsdafdsa dfasfda asfdasf asdfsaf ";
System.out.println(s.trim());
But there are no direct methods for L-TRIM or R-TRIM individually.
Below are the some of the implementations of L-TRIM and R-TRIM:
Method1:
Implementing using Regular Expressions
String ltrim = s.replaceAll("^\\s+","");
String rtrim = s.replaceAll("\\s+$","");
very simple right..... :)
Method2:
If you have to do it often, you can create and compile a pattern for better performance
private final static Pattern LTRIM = Pattern.compile("^\\s+");
private final static Pattern RTRIM = Pattern.compile("\\s+$");
public static String ltrim(String s) {
return LTRIM.matcher(s).replaceAll("");
}
public static String rtrim(String s) {
return RTRIM.matcher(s).replaceAll("");
}
Method3:
Implemented by removing the white spaces.
This method is least prefered.
public static String ltrim3(String s) {
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))){
i++;
}
return s.substring(i);
}
public static String rtrim3(String s) {
int i = s.length()-1;
while (i >= 0 && Character.isWhitespace(s.charAt(i))) {
i--;
}
return s.substring(0,i+1);
}
Thank you soo much @Cindy Dy :)
ReplyDeleteThanks for this post.. helped a lot...
ReplyDeleteThank you Deepak :)
Delete