Organizational Research By

Surprising Reserch Topic

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)))
         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
asked Jun 11, 2015 in Java Interview Questions by rajesh
0 votes
37 views



Related Hot Questions



Government Jobs Opening


...