beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

How to remove only trailing spaces of a string in Java

By Chaitanya Singh | Filed Under: String Formatting

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 [email protected]
#    I'm [email protected]

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

Enjoyed this post? Try these related posts

  1. java – Left padding a String with Spaces and Zeros
  2. java – Right padding a String with Spaces and Zeros

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap