How to remove only trailing spaces of a string in Java

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)))
    return str.substring( 0, len);

#  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

asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.