Open In App

Trim (Remove leading and trailing spaces) a string in Java

Given a string, remove all the leading and trailing spaces from the string and return it.

Examples:



Input :  str = "   Hello World   "
Output : str = "Hello World"

Input :  str = "      Hey  there    Joey!!!      "
Output : str = "Hey  there    Joey!!!"

How it works?
For space character the unicode value is ‘\u0020’. This method checks for this unicode value before and after the string and if it exists then eliminates the spaces(leading and trailing) and returns the string (without leading and trailing spaces).




public class remove_spaces
{
    public static void main(String args[])
    {
        String str1 = "  Hello World  ";
        System.out.println(str1);
        System.out.println(str1.trim());
  
        String str2 = "      Hey  there    Joey!!!      ";
        System.out.println(str2);
        System.out.println(str2.trim());
    }
}

Output:

  Hello World  
Hello World
      Hey  there    Joey!!!  
Hey  there    Joey!!!    



Article Tags :