XtraStudy Header LOGO Home

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

Tags : #Java, #trim(), #remove_space   Author : Admin
Updated : 11-Jun-2022


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

Q. 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!!!"

  • We can eliminate the leading and trailing spaces of a string in Java with the help of trim().
  • trim() method is defined under the String class of java.lang package.
  • It does not eliminated the middle spaces of the string.
  • By calling the trim() method, a new String object is returned.
  • It doesn’t replace the value of String object. Therefore if we want the access to the new String object, we just need to reassign it to the old String or assign it to a new variable.

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!!! 

 

 

 

 XtraStudy ADVT Skill India
Likes
Comments (0)