In this tutorial we will learn how to trim trailing spaces from the string but not leading spaces. Here is the complete code:
class TrimBlanksExample { public static void main(String[] args) { System.out.println("#"+trimTrailingBlanks(" How are you?? ")+"@"); System.out.println("#"+trimTrailingBlanks(" I'm Fine. ")+"@"); } public static String trimTrailingBlanks( String str) { if( str == null) return null; int len = str.length(); for( ; len > 0; len--) { if( ! Character.isWhitespace( str.charAt( len - 1))) break; } return str.substring( 0, len); } }
Output:
# How are you??@ # I'm Fine.@
As you can see that there is no space between the string and “@” that shows that the trailing spaces have been removed from the String. Also, there are spaces between “#” and String in the output which shows that leading blanks are not trimmed off from string.
References:
substring() method
charAt() method
length() method
isWhitespace() method
Leave a Reply