Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good alternative of LTRIM and RTRIM in Java?

Tags:

java

string

trim

What is a good alternative of JavaScript ltrim() and rtrim() functions in Java?

like image 742
yegor256 Avatar asked Mar 22 '13 09:03

yegor256


People also ask

Which type of trim is used in Java?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

How do you do Ltrim and Rtrim in Java?

ltrim is then a substring starting at the first non-whitespace character. Or for R-Trim, we'll read our string from right to left until we run into a non-whitespace character: int i = s. length()-1; while (i >= 0 && Character.

What is replace method in Java?

Java String replace() Method The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.

How do you get rid of leading and trailing spaces in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.


2 Answers

Using regex may be nice, but it's quite a lot slower than a simple trimming functions:

public static String ltrim(String s) {     int i = 0;     while (i < s.length() && Character.isWhitespace(s.charAt(i))) {         i++;     }     return s.substring(i); }  public static String rtrim(String s) {     int i = s.length()-1;     while (i >= 0 && Character.isWhitespace(s.charAt(i))) {         i--;     }     return s.substring(0,i+1); } 

Source: http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html

Also, there are some libraries providing such functions. For example, Spring StringUtils. Apache Commons StringUtils provides similar functions too: strip, stripStart, stripEnd

StringUtils.stripEnd("abc  ", null)    = "abc" 
like image 42
bezmax Avatar answered Sep 17 '22 13:09

bezmax


With a regex you could write:

String s = ... String ltrim = s.replaceAll("^\\s+",""); String rtrim = s.replaceAll("\\s+$",""); 

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+");  public static String ltrim(String s) {     return LTRIM.matcher(s).replaceAll(""); } 

From a performance perspective, a quick micro benchmark shows (post JIT compilation) that the regex approach is about 5 times slower than the loop (0.49s vs. 0.11s for 1 million ltrim).

I personally find the regex approach more readable and less error prone but if performance is an issue you should use the loop solution.

like image 96
assylias Avatar answered Sep 17 '22 13:09

assylias