This is a tutorial for java beginners who are struggling on the String trim() method. I have seen many students wondering about how to use the Java String trim method.
Here I am trying to show some simple exercises which can be used for learning and understanding String trim and few other methods.
Java.lang.String class contains the trim() method, which can be used to trim a string from left and right both sides. So for example if you have a string [” This is a String “] then calling a trim() method on this string will convert it to [“This is a String”].
1. Simplest thing first – Using the trim() method
Simplest thing to do is to call trim method on String object itself like shown below.
String sentense = " Trim A String With Space "; sentense = sentense.trim(); System.out.println("[" + sentense + "]");
If you run the above code the output will be
[Trim A String With Space]
If you haven’t noticed it here, I have assigned the value back to the same variable ( sentense = sentense.trim(); ). This is required because String class is immutable and a new object is created every time you call trim method on a string object.
So if you would do like this
String sentense = " Trim A String With Space "; sentense.trim(); System.out.println("[" + sentense + "]");
Then you will not see the trimmed string as the actual sentance reference is still pointing to old object. As the String objects are immutable all String class methods will have same behavior so you need to keep this in mind everytime you are doing any operation on a String.
If you run the above code the output will be
[ Trim A String With Space ]
Lets play more with the trim method now.
2. How about trimming all spaces in a string?
You must have noticed here that the spaces in between the string are not removed when you are using trim() method,
which will not be required most of the time but will be good to try your string manipulation skills.
Below is a simple method which can trim all spaces in a string.
/** * This method is for removing all space characters * from a String including the spaces in between the words. * e.g. for input " Test String " * result is "TestString" * Not very commonly used but good for practice exercise for students. * @param s * @return */ public static String trimAll(String s ) { if(s!=null) { return s.replaceAll(" ", ""); } return s; }
3. How about trimming all spaces at the beginning of a string?
If you are familiar with Oracle you must have seen a ltrim() function in, which can trim all spaces at the beginning of a string.
We can call this function as ltrim as its going to trim all spaces at the left side of a string.
Below is a simple method which can trim all spaces at the beginning of a string.
/** * This is a ltrim implementation for a string. * It trims all spaces at only beginning of the String(not end). * e.g. for input " Test String " * result is "Test String " * Not very commonly used but good for practice exercise for students. * People who are familiar with Oracle may also try to look for this * type of function in java but its not really used much as such in * practical programming world. * @param s * @return */ public static String ltrim(String s) { int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } return s.substring(i); }
4. How about trimming all spaces at the end of a string? Again, if you are familiar with Oracle you must have seen a rtrim() function in, which can trim all spaces at the end of a string. We can call this function as rtrim as its going to trim all spaces at the right side of a string. Below is a simple method which can trim all spaces at the end of a string.
/** * This is a rtrim implementation for a string. * It trims all spaces only at the end of the String(not beginning). * e.g. for input " Test String " * result is " Test String" * Not very commonly used but good for practice exercise for students. * People who are familiar with Oracle may also try to look for this * type of function in java but its not really used much as such in * practical programming world. * @param s * @return */ 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); }
5. Lets test them all Here is a simple test code, which will demonstrate all the examples above
public static void main(String[] args) { String sentense = " Trim A String With Space "; System.out.println("[" + trimAll(sentense) + "]"); System.out.println("[" + ltrim(sentense) + "]"); System.out.println("[" + rtrim(sentense) + "]"); sentense.trim(); System.out.println("[" + sentense + "]"); sentense = sentense.trim(); System.out.println("[" + sentense + "]"); }
If you run the above code the output will be
[TrimAStringWithSpace] [Trim A String With Space ] [ Trim A String With Space] [ Trim A String With Space ] [Trim A String With Space]
the trimming should include white spaces, like spaces and tabs. It should be done with regular expressions.
I agree, only trimming spaces may not be sufficient. How about a regEx trim to be included on same post? just a thought..
Why are you creating a string everytime through the while loop? I'm sure you can do better than what I have below by converting the string into a char array, but the following at least uses Character.isWhitespace() and doesn't create all those Strings.
public static String ltrim(String s) {
int i = 0;
while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
i++;
}
return s.substring(i +1);
}
Or just use org.apache.commons.lang.StringUtils.stripStart(s, null);
@Anonymous – As per your suggestion I have updated the post with more efficient version suggested by you. Just a small correction in your code. I have replace this line
return s.substring(i +1);
with
return s.substring(i);
The ltrim() and rtrim() both methods have been updated to the more efficient version as suggested by comments. Thanks for responses.
Let me know if there are any other improvement areas.