Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Java String trim() method is a built-in function used to eliminate leading and trailing spaces. We can also use this method to trim characters from Java String.

Syntax 

The syntax of the trim in java is:

string.trim()

Here, a string is an object of the String class.

Parameters

the trim in java doesn't take any parameters

Return Value

  • trim function in java returns a string without trailing and leading whitespaces.
  • trim function in java returns the original string if there is no whitespace at the start or the end of the string.

Internal Implementation

public String trim() {    
        int len = value.length;    
        int st = 0;    
        char[] val = value;    /* avoid getfield opcode */
    
        /* Remove leading Space */
        while ((st < len) && (val[st] <= ' ')) {    
            st++;    
        }
  
        /* Remove trailing Space */
        while ((st < len) && (val[len - 1] <= ' ')) {    
            len--;    
        }    
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this; 

Must Read: Java System Out Println

Examples

Example1

In this example, we will know how to remove the spaces from both ends using the trim in java.

class Main{
 
    // driver code
    public static void main(String args[])
    {
 
        // trims the trailing and leading spaces
        String s = "   Hello ninjas!  ";
        System.out.println(s.trim());
 
    }
}

Output

Hello ninjas!

 

Example2

This is another example to understand how the trim in java works. We will print the String length before and after using trim in java program.

// program to demonstrate working trim in java
import java.io.*;
class Main{
   public static void main (String[] args) {
       
     String s1 = "   this string has leading and trailing spaces   ";
     
     // Before Trim() method
     System.out.println("Before Java String Trim() method - ");
     System.out.println("String - "+s1);
     System.out.println("Length - "+s1.length());
     
     // applying trim() method on string s1
     s1=s1.trim();
     
     // After Trim() method
     System.out.println("\nAfter Java String Trim() method - ");
     System.out.println("String - "+s1);
     System.out.println("Length - "+s1.length());
     
   }
}

Output

Before Java String Trim() method -

String -       this string has leading and trailing spaces

Length - 49

 

After Java String Trim() method -

String - this string has leading and trailing spaces

Length - 43

 

Must Read Type Conversion in Java

Remove All Whitespace Characters

For removing all whitespace characters from a string, we use the String replaceAll() method.

class Main {
  public static void main(String[] args) {
    String str = "Hello\nNinzas \n\n ";
    String result;

    // replace all whitespace characters with empty string
    result = str.replaceAll("\\s", "");

    System.out.println(result);
  }
}

Output

Hello Ninzas

String strip() vs Java String trim() Method

  • From Java 11, many new methods in the string class came. Among them is the strip() method that does the same job as the trim in java.
  • However, the strip() method uses Character.isWhitespace() method to check if the Character is whitespace. 
  • This method uses Unicode code points, whereas the trim in java identifies any character having a codepoint value less than or equal to 'U+0020' as a whitespace character.
  • The strip() method is recommended to remove whitespaces because it uses the Unicode standard.


Must Read String Args in Java

FAQs

  1. What is the purpose of the trim function in Java?
    The trim in java removes whitespace from both ends of a string and returns a new String without modifying the original strings. Here, the whitespace context is all the whitespace characters (space, tab, no-break space, etc.)
  2. How does the trim in java work?
    The trim in java removes all leading and trailing whitespace characters from the current string. Each trailing and leading trim operation stops when it encounters a non-white-space character. For example, if the current string is "pqr xyz, "the Trim method returns "pqr xyz."
  3. Does trim in Java remove the newline?
    The function trim in java is used to get rid of whitespaces (spaces, newlines, etc.) from the beginning and end of the string. It also removes all the line terminator characters (LF, CR, etc.)
  4. How do you remove white spaces from a string?
    The replaceAll() method of the String class replaces every substring of that particular string with having matches in the given regular expression with the given replacement. You can remove white spaces from a string by replacing" "with."
  5. How do we remove any part of a string?
    The removal of a part of the string can be done by using REPLACE() function. We can consider this function only if we have an idea about removing the exact particular Character of the String.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Key Takeaways

In this article, we learned about trim in java and its implementation. This method omits spaces from both ends of the String in Java. We have also seen some examples to understand better how this method works, and at the end of this blog, we learned about how Remove() and strip() functions work in Java.

Check out this problem - Multiply Strings

We hope that this blog has helped you enhance your knowledge regarding trim function in java and if you want to learn more, check out articles on Coding Ninjas Studio. Do upvote our blogs to help other ninjas grow. 

Happy Coding!

Topics covered
1.
Introduction
1.1.
Syntax 
1.2.
Parameters
1.3.
Return Value
1.4.
Internal Implementation
1.5.
Examples
1.6.
Remove All Whitespace Characters
1.7.
String strip() vs Java String trim() Method
2.
FAQs
3.
Key Takeaways